@cubicecho/discovery-core 0.1.0 → 1.1.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/LICENSE +0 -0
- package/README.md +67 -36
- package/_agents/docs/01-install.md +25 -0
- package/_agents/docs/building-on-core.md +11 -0
- package/_agents/docs/common-mistakes.md +79 -0
- package/_agents/docs/fetching-documents.md +36 -0
- package/_agents/docs/mdns-advertising.md +72 -0
- package/_agents/docs/mdns-browsing.md +94 -0
- package/_agents/docs/serving-documents.md +65 -0
- package/_agents/docs/txt-records.md +22 -0
- package/dist/client/fetch-json.d.ts +0 -0
- package/dist/client/fetch-json.js +0 -0
- package/dist/core/defaults.d.ts +2 -0
- package/dist/core/defaults.js +1 -0
- package/dist/core/errors.d.ts +0 -0
- package/dist/core/errors.js +0 -0
- package/dist/core/host-slug.d.ts +0 -0
- package/dist/core/host-slug.js +0 -0
- package/dist/core/parse.d.ts +0 -0
- package/dist/core/parse.js +0 -0
- package/dist/core/spec-version.d.ts +0 -0
- package/dist/core/spec-version.js +0 -0
- package/dist/index.d.ts +0 -0
- package/dist/index.js +0 -0
- package/dist/mdns/advertise-service.d.ts +0 -0
- package/dist/mdns/advertise-service.js +0 -0
- package/dist/mdns/advertiser.d.ts +0 -0
- package/dist/mdns/advertiser.js +0 -0
- package/dist/mdns/browse.d.ts +0 -0
- package/dist/mdns/browse.js +0 -0
- package/dist/mdns/entry-tracker.d.ts +10 -3
- package/dist/mdns/entry-tracker.js +33 -5
- package/dist/mdns/load-bonjour.d.ts +0 -0
- package/dist/mdns/load-bonjour.js +0 -0
- package/dist/mdns/report-error.d.ts +0 -0
- package/dist/mdns/report-error.js +0 -0
- package/dist/mdns/responder.d.ts +0 -0
- package/dist/mdns/responder.js +0 -0
- package/dist/mdns/txt.d.ts +1 -1
- package/dist/mdns/txt.js +8 -3
- package/dist/mdns/watch-entries.d.ts +2 -1
- package/dist/mdns/watch-entries.js +3 -2
- package/dist/mdns.d.ts +0 -0
- package/dist/mdns.js +0 -0
- package/dist/serve/document-response.d.ts +0 -0
- package/dist/serve/document-response.js +0 -0
- package/dist/serve/node-handler.d.ts +0 -0
- package/dist/serve/node-handler.js +0 -0
- package/dist/serve/request-origin.d.ts +0 -0
- package/dist/serve/request-origin.js +0 -0
- package/llms.txt +82 -70
- package/package.json +11 -9
package/LICENSE
CHANGED
|
File without changes
|
package/README.md
CHANGED
|
@@ -1,44 +1,75 @@
|
|
|
1
|
+
<!-- AI agents: read llms.txt and _agents/docs/ for the full, version-matched API. -->
|
|
1
2
|
# @cubicecho/discovery-core
|
|
2
3
|
|
|
3
|
-
The shared core of the cubicecho discovery packages
|
|
4
|
+
The shared core of the cubicecho discovery packages: serving and fetching public discovery documents, and
|
|
5
|
+
advertising and browsing over mDNS.
|
|
6
|
+
|
|
7
|
+
Apps don't install this directly. They use
|
|
4
8
|
[`@cubicecho/mcp-discovery`](https://github.com/cubicecho/mcp-discovery) to be found as an MCP server, or
|
|
5
9
|
[`@cubicecho/graphql-mdns-discovery`](https://github.com/cubicecho/graphql-mdns-discovery) to be found as a
|
|
6
|
-
GraphQL API. Both
|
|
7
|
-
|
|
10
|
+
GraphQL API. Both are built on this package, so an app that uses them together gets one mDNS responder and
|
|
11
|
+
middleware that don't overlap.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
8
14
|
|
|
9
|
-
```
|
|
15
|
+
```sh
|
|
10
16
|
npm install @cubicecho/discovery-core zod
|
|
11
|
-
npm install bonjour-service # only for
|
|
17
|
+
npm install bonjour-service # only for @cubicecho/discovery-core/mdns
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Node 22 or later.
|
|
21
|
+
|
|
22
|
+
## Quick start
|
|
23
|
+
|
|
24
|
+
Serve one public document on its own path, with CORS, caching and ETags handled:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { createServer } from 'node:http';
|
|
28
|
+
import { answeringMiddleware, documentHandler, requestOrigin, requestPath } from '@cubicecho/discovery-core';
|
|
29
|
+
|
|
30
|
+
const serve = documentHandler('application/json', (request) => ({
|
|
31
|
+
specVersion: '1.0',
|
|
32
|
+
url: `${requestOrigin(request)}/api`,
|
|
33
|
+
}));
|
|
34
|
+
|
|
35
|
+
const discovery = answeringMiddleware(async (request, response) => {
|
|
36
|
+
const isMine = requestPath(request) === '/.well-known/example.json';
|
|
37
|
+
if (isMine) {
|
|
38
|
+
await serve(request, response);
|
|
39
|
+
}
|
|
40
|
+
return isMine;
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
createServer((request, response) => {
|
|
44
|
+
discovery(request, response, (error) => {
|
|
45
|
+
response.writeHead(error ? 500 : 404);
|
|
46
|
+
response.end();
|
|
47
|
+
});
|
|
48
|
+
}).listen(3000);
|
|
12
49
|
```
|
|
13
50
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
-
|
|
39
|
-
so a request you don't own goes to `next()`.
|
|
40
|
-
- Give your exports names of their own (`advertiseGraphql`, not `advertise`), so an app can import two
|
|
41
|
-
discovery packages without aliasing. Re-export the shared classes from here, so `instanceof` works
|
|
42
|
-
across packages.
|
|
43
|
-
- Keep `zod` and `bonjour-service` as peer dependencies with the ranges used here (`>=4.1`, `>=1.4`), so
|
|
44
|
-
an app installs one copy of each.
|
|
51
|
+
Then `curl http://localhost:3000/.well-known/example.json`. In Express, it's `app.use(discovery)`.
|
|
52
|
+
|
|
53
|
+
## Why one responder per process
|
|
54
|
+
|
|
55
|
+
When bonjour-service stops a service, it also withdraws the address records that every other service on the
|
|
56
|
+
host uses, so peers lose the address of a service that is still up. Here, everything in a process shares one
|
|
57
|
+
responder, which puts the shared records straight back. [Advertising on the
|
|
58
|
+
LAN](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/mdns-advertising.md) has the details.
|
|
59
|
+
|
|
60
|
+
## Documentation
|
|
61
|
+
|
|
62
|
+
- [llms.txt](https://cdn.jsdelivr.net/npm/@cubicecho/discovery-core/llms.txt), the index of every page and export
|
|
63
|
+
- [Install and entry points](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/01-install.md)
|
|
64
|
+
- [Serving a document](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/serving-documents.md)
|
|
65
|
+
- [Fetching a document](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/fetching-documents.md)
|
|
66
|
+
- [Advertising on the LAN](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/mdns-advertising.md)
|
|
67
|
+
- [Browsing the LAN](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/mdns-browsing.md)
|
|
68
|
+
- [TXT records](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/txt-records.md)
|
|
69
|
+
- [Building a discovery package](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/building-on-core.md)
|
|
70
|
+
- [Common mistakes](https://github.com/cubicecho/discovery-core/blob/main/_agents/docs/common-mistakes.md)
|
|
71
|
+
- [Changelog](https://github.com/cubicecho/discovery-core/blob/main/CHANGELOG.md)
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
|
|
75
|
+
[MIT](https://github.com/cubicecho/discovery-core/blob/main/LICENSE)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Install and entry points
|
|
2
|
+
|
|
3
|
+
How to depend on `@cubicecho/discovery-core` from a discovery package, which of its two entry points to import, and when `bonjour-service` is needed. An app that only wants to be found installs `@cubicecho/mcp-discovery` or `@cubicecho/graphql-mdns-discovery` instead.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @cubicecho/discovery-core
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Keep `zod` and `bonjour-service` as peer dependencies of the package you build, so an app installs one copy of each:
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"peerDependencies": { "zod": ">=4.1", "bonjour-service": ">=1.4" },
|
|
14
|
+
"peerDependenciesMeta": { "bonjour-service": { "optional": true } }
|
|
15
|
+
}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
| Import | Holds | Needs |
|
|
19
|
+
| --- | --- | --- |
|
|
20
|
+
| `@cubicecho/discovery-core` | serving and fetching documents, errors, `hostSlug` | `zod` |
|
|
21
|
+
| `@cubicecho/discovery-core/mdns` | advertising and browsing on the LAN | `bonjour-service` |
|
|
22
|
+
|
|
23
|
+
Give your own package the same split: nothing reachable from its root entry point imports `@cubicecho/discovery-core/mdns`. `bonjour-service` is loaded on first use, so a missing install surfaces as a rejected promise from the first mDNS call (`mDNS needs the optional peer dependency bonjour-service: npm install bonjour-service`).
|
|
24
|
+
|
|
25
|
+
The package is ESM only and runs on Node 22 or later.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Building a discovery package
|
|
2
|
+
|
|
3
|
+
The rules a package built on `@cubicecho/discovery-core` follows so that an app can use it beside the other discovery packages without clashes.
|
|
4
|
+
|
|
5
|
+
- **Its own service type and TXT layout.** Use a DNS-SD type of your own (`mcp`, `graphql`) and a TXT layout versioned by `txtvers`. See [TXT records](txt-records.md).
|
|
6
|
+
- **Its own well-known path, and only that path.** Wrap the handler in `answeringMiddleware` and check `requestPath`, so a request you don't own goes to `next()`. See [serving a document](serving-documents.md).
|
|
7
|
+
- **Its own export names.** Export `advertiseGraphql`, not `advertise`, so an app can import two discovery packages without aliasing.
|
|
8
|
+
- **The shared classes, re-exported.** Re-export `DiscoveryError`, `DocumentFetchError` and `InvalidDocumentError` from here instead of declaring your own, so `instanceof` works across packages.
|
|
9
|
+
- **The same peers.** Keep `zod` (`>=4.1`) and `bonjour-service` (`>=1.4`, optional) as peer dependencies. See [install](01-install.md).
|
|
10
|
+
- **The shared responder.** Advertise and browse through this package only; never construct `Bonjour`. See [advertising](mdns-advertising.md#one-responder-per-process).
|
|
11
|
+
- **An mDNS entry point of its own.** Keep mDNS behind `./mdns`, so an app that only serves a document doesn't need `bonjour-service`.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Common mistakes
|
|
2
|
+
|
|
3
|
+
Mistakes that compile and mostly fail silently when building on `@cubicecho/discovery-core`, each with what happens and the fix.
|
|
4
|
+
|
|
5
|
+
## Returning nothing from an answeringMiddleware function
|
|
6
|
+
|
|
7
|
+
Only a literal `false` calls `next()`. A function that resolves `undefined` for a request it doesn't own (possible from JavaScript or through a cast) leaves that request hanging with no error. Return a boolean on every path:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { answeringMiddleware, documentHandler, requestPath } from '@cubicecho/discovery-core';
|
|
11
|
+
|
|
12
|
+
const serve = documentHandler('application/json', () => ({ specVersion: '1.0' }));
|
|
13
|
+
|
|
14
|
+
export const middleware = answeringMiddleware(async (request, response) => {
|
|
15
|
+
const isMine = requestPath(request) === '/.well-known/example.json';
|
|
16
|
+
if (isMine) {
|
|
17
|
+
await serve(request, response);
|
|
18
|
+
}
|
|
19
|
+
return isMine;
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Mounting documentHandler with app.use
|
|
24
|
+
|
|
25
|
+
It checks no path, so it answers every URL in the app with the document. Wrap it in `answeringMiddleware` with a `requestPath` check, as above, or mount it on an exact route.
|
|
26
|
+
|
|
27
|
+
## Passing documentHandler to http.createServer
|
|
28
|
+
|
|
29
|
+
It returns a promise that rejects when the document source throws, and `http.createServer` ignores that promise, so the rejection is unhandled and ends the process. Use `answeringMiddleware`, which sends errors to `next`, or catch it:
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import { createServer } from 'node:http';
|
|
33
|
+
import { documentHandler } from '@cubicecho/discovery-core';
|
|
34
|
+
|
|
35
|
+
const handler = documentHandler('application/json', () => ({ specVersion: '1.0' }));
|
|
36
|
+
|
|
37
|
+
createServer((request, response) => {
|
|
38
|
+
handler(request, response).catch(() => {
|
|
39
|
+
response.writeHead(500);
|
|
40
|
+
response.end();
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Opening a second Bonjour instance, or calling unpublishAll
|
|
46
|
+
|
|
47
|
+
Stopping one service then sends goodbyes for the host's shared address records, and peers drop the address of services that are still up. Go through `advertiseService`, or `acquireResponder` with `lease.unpublish(service)`.
|
|
48
|
+
|
|
49
|
+
## Writing a TXT flag as true or as a bare key
|
|
50
|
+
|
|
51
|
+
`readTxtFlag` is true only for the string `'1'`. A `tls` flag written any other way reads as off, and clients build `http://` URLs for an HTTPS host.
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
import { FLAG_ON, TXT_TLS_KEY } from '@cubicecho/discovery-core/mdns';
|
|
55
|
+
|
|
56
|
+
export const txt = { txtvers: '1', [TXT_TLS_KEY]: FLAG_ON };
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Using requestOrigin behind a TLS-terminating proxy
|
|
60
|
+
|
|
61
|
+
It reads the scheme from the socket, which is plain HTTP there, so the document names `http://` URLs. Build the URLs from the configured public URL instead:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { documentHandler, requestOrigin } from '@cubicecho/discovery-core';
|
|
65
|
+
|
|
66
|
+
const publicUrl: string | undefined = process.env.PUBLIC_URL;
|
|
67
|
+
|
|
68
|
+
export const handler = documentHandler('application/json', (request) => ({
|
|
69
|
+
url: `${publicUrl ?? requestOrigin(request)}/api`,
|
|
70
|
+
}));
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Returning a failed entry without isFailed
|
|
74
|
+
|
|
75
|
+
`readHost` results replace what was known about a host. An entry left out of `entries` is reported down, even when its read failed for a moment and its error is in `failures`. Return `isFailed` so the tracker keeps it, as in [watch what the hosts list](mdns-browsing.md#watch-what-the-hosts-list), or reject when the whole document couldn't be read.
|
|
76
|
+
|
|
77
|
+
## Expecting sync to apply a new port
|
|
78
|
+
|
|
79
|
+
`Advertiser.sync()` leaves a running announcement alone, so a port or name that changed is not announced. Sync with `isWanted` false, then true.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# Fetching a document
|
|
2
|
+
|
|
3
|
+
Fetch and validate a discovery document from a host nobody has vetted, bounded in time and size, and tell the failures apart.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { DocumentFetchError, fetchJson, InvalidDocumentError, parseDocument, specVersionSchema } from '@cubicecho/discovery-core';
|
|
7
|
+
import { z } from 'zod';
|
|
8
|
+
|
|
9
|
+
const exampleSchema = z.object({ specVersion: specVersionSchema(1), url: z.url() });
|
|
10
|
+
|
|
11
|
+
export async function readExample(url: string, signal?: AbortSignal) {
|
|
12
|
+
try {
|
|
13
|
+
const json = await fetchJson(url, 'application/json', { timeoutMs: 2000 }, { signal });
|
|
14
|
+
return parseDocument(exampleSchema, json, 'example document', url);
|
|
15
|
+
} catch (error) {
|
|
16
|
+
if (error instanceof DocumentFetchError) {
|
|
17
|
+
console.warn(`unreachable (${error.status ?? 'no response'}): ${error.message}`);
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
if (error instanceof InvalidDocumentError) {
|
|
21
|
+
console.warn(error.message);
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- **Limits.** `fetchJson` gives up after `FETCH_DEFAULTS.timeoutMs` (5 seconds, headers and body together) and refuses a body over `maxDocumentBytes` (1 MiB). Change either with the third argument.
|
|
30
|
+
- **`fetchJson` doesn't validate.** It returns `unknown`; pass it to `parseDocument`.
|
|
31
|
+
- **`specVersionSchema(1)`** accepts any `1.x` and refuses every other major.
|
|
32
|
+
- **Errors.** Both classes extend `DiscoveryError`, whose `source` says where the document came from. `DocumentFetchError.status` is the HTTP status, or null when no response arrived. `InvalidDocumentError` covers a body that isn't JSON and one that doesn't match the schema.
|
|
33
|
+
- **Cancelling.** An aborted `signal` also surfaces as a `DocumentFetchError` with a null status; the abort is its `cause`.
|
|
34
|
+
- **`fetch` option.** The fourth argument also takes a `fetch`, for a proxy-aware one or a test double.
|
|
35
|
+
|
|
36
|
+
Validating says the document is well formed, not that its host is trustworthy. Decide what to connect to by your own policy.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Advertising on the LAN
|
|
2
|
+
|
|
3
|
+
Announce a DNS-SD service over mDNS, keep the announcement in step with a live setting, and share one responder across everything in the process.
|
|
4
|
+
|
|
5
|
+
## Advertise once
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { AdvertiseError, advertiseService, TXT_VERSION_KEY } from '@cubicecho/discovery-core/mdns';
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
const advertisement = await advertiseService({
|
|
12
|
+
type: 'example', // announced as _example._tcp
|
|
13
|
+
name: 'nas',
|
|
14
|
+
port: 3000,
|
|
15
|
+
txt: { [TXT_VERSION_KEY]: '1', path: '/api' },
|
|
16
|
+
onError: (error) => console.warn(error.message),
|
|
17
|
+
});
|
|
18
|
+
process.once('SIGTERM', () => void advertisement.stop());
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error instanceof AdvertiseError) {
|
|
21
|
+
console.warn(error.message);
|
|
22
|
+
} else {
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
It resolves once the announcement has gone out, and rejects with `AdvertiseError` after `announceTimeoutMs` (5 seconds), most often because the instance name is already taken on the network. `stop()` sends the goodbyes, so call it on shutdown.
|
|
29
|
+
|
|
30
|
+
`type` has no underscores or protocol. `host` defaults to the machine's hostname plus `.local`. In a container, use host networking: Docker's default bridge drops multicast.
|
|
31
|
+
|
|
32
|
+
## Follow a setting
|
|
33
|
+
|
|
34
|
+
`createAdvertiser` starts and stops the announcement to match a setting. Nothing is announced until the first `sync()`.
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { type AdvertiserOptions, advertiseService, createAdvertiser } from '@cubicecho/discovery-core/mdns';
|
|
38
|
+
|
|
39
|
+
const settings = { lanDiscovery: true };
|
|
40
|
+
|
|
41
|
+
const advertiser = createAdvertiser<AdvertiserOptions>({
|
|
42
|
+
isWanted: () => settings.lanDiscovery,
|
|
43
|
+
options: () => ({ name: 'nas', port: 3000 }),
|
|
44
|
+
log: (message) => console.log(message),
|
|
45
|
+
start: ({ name, port, onError }) =>
|
|
46
|
+
advertiseService({ type: 'example', name, port, txt: { txtvers: '1' }, onError }),
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
await advertiser.sync(); // call again whenever the setting changes
|
|
50
|
+
await advertiser.close(); // on shutdown
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Name the options type: without it, TypeScript infers it from `options` and `start` has no `onError`.
|
|
54
|
+
|
|
55
|
+
A failed start is logged, not thrown, and the next `sync()` tries again. `sync()` doesn't restart a running announcement, so to apply a new port or name, sync with `isWanted` false and then true.
|
|
56
|
+
|
|
57
|
+
## One responder per process
|
|
58
|
+
|
|
59
|
+
Every advertisement and browse goes through `acquireResponder()`, a reference-counted `bonjour-service` instance kept on `globalThis`, so two copies of this package in one process still share it. The last release closes the socket. It exists because stopping a service on one Bonjour instance withdraws the host's address records for every other service on that host.
|
|
60
|
+
|
|
61
|
+
Use the lease directly only for what `advertiseService` and `watchServices` don't cover:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { acquireResponder } from '@cubicecho/discovery-core/mdns';
|
|
65
|
+
|
|
66
|
+
const lease = await acquireResponder((error) => console.warn(error.message));
|
|
67
|
+
const service = lease.publish({ name: 'nas', type: 'example', port: 3000, txt: { txtvers: '1' } });
|
|
68
|
+
await lease.unpublish(service); // this service only
|
|
69
|
+
await lease.release(); // withdraws whatever this lease still publishes
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Stop a browser from `lease.find(...)` before releasing. `responderHolders()` is the number of open leases, for a test that checks nothing leaked.
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# Browsing the LAN
|
|
2
|
+
|
|
3
|
+
Find hosts advertising a DNS-SD service type, once or continuously, and turn those hosts into the entries their documents list.
|
|
4
|
+
|
|
5
|
+
## Find or watch hosts
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { findServices, readTxtFlag, readTxtPath, TXT_TLS_KEY, toFoundHost, watchServices } from '@cubicecho/discovery-core/mdns';
|
|
9
|
+
import type { FoundService } from '@cubicecho/discovery-core/mdns';
|
|
10
|
+
|
|
11
|
+
const browse = {
|
|
12
|
+
type: 'example',
|
|
13
|
+
toHost: (service: FoundService) =>
|
|
14
|
+
toFoundHost(service, (txt) => ({
|
|
15
|
+
tls: readTxtFlag(txt, TXT_TLS_KEY),
|
|
16
|
+
path: readTxtPath(txt, 'path', '/api'),
|
|
17
|
+
})),
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Listens for 3 seconds, then answers.
|
|
21
|
+
const hosts = await findServices(browse);
|
|
22
|
+
for (const { name, origin, txt } of hosts) {
|
|
23
|
+
console.log(name, `${origin}${txt.path}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Reports hosts until stopped.
|
|
27
|
+
const watch = await watchServices(browse, {
|
|
28
|
+
onUp: (host) => console.log('up', host.origin),
|
|
29
|
+
onDown: (host) => console.log('down', host.name),
|
|
30
|
+
onError: (error) => console.warn(error.message),
|
|
31
|
+
});
|
|
32
|
+
await watch.stop();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`onUp` also fires when a known host changes its record, so treat it as an upsert by `name`. `toFoundHost` builds `origin` from the first IPv4 address, or the mDNS name when there is none, with `https` when the parsed record has `tls: true`.
|
|
36
|
+
|
|
37
|
+
## Watch what the hosts list
|
|
38
|
+
|
|
39
|
+
`watchEntries` reads each host's document, and here what that document points at, as hosts come and go, re-reads every host every `refreshMs` (5 minutes), and reports the differences.
|
|
40
|
+
|
|
41
|
+
```ts
|
|
42
|
+
import { DiscoveryError, fetchJson, parseDocument } from '@cubicecho/discovery-core';
|
|
43
|
+
import { type FoundHost, readTxtFlag, toFoundHost, watchEntries } from '@cubicecho/discovery-core/mdns';
|
|
44
|
+
import { z } from 'zod';
|
|
45
|
+
|
|
46
|
+
const documentSchema = z.object({ apis: z.array(z.object({ name: z.string(), url: z.string() })) });
|
|
47
|
+
const detailsSchema = z.object({ title: z.string() });
|
|
48
|
+
type Host = FoundHost<{ tls: boolean }>;
|
|
49
|
+
type Api = { host: string; name: string; url: string; title: string };
|
|
50
|
+
|
|
51
|
+
const watch = await watchEntries<Host, Api>(
|
|
52
|
+
{
|
|
53
|
+
type: 'example',
|
|
54
|
+
toHost: (service) => toFoundHost(service, (txt) => ({ tls: readTxtFlag(txt, 'tls') })),
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
readHost: async (host) => {
|
|
58
|
+
const url = `${host.origin}/.well-known/example.json`;
|
|
59
|
+
const json = await fetchJson(url, 'application/json');
|
|
60
|
+
const { apis } = parseDocument(documentSchema, json, 'example document', url);
|
|
61
|
+
const entries: Api[] = [];
|
|
62
|
+
const failures: Error[] = [];
|
|
63
|
+
const failedNames = new Set<string>();
|
|
64
|
+
for (const { name, url: cardUrl } of apis) {
|
|
65
|
+
try {
|
|
66
|
+
const details = parseDocument(detailsSchema, await fetchJson(cardUrl, 'application/json'), 'API', cardUrl);
|
|
67
|
+
entries.push({ host: host.name, name, url: cardUrl, ...details });
|
|
68
|
+
} catch (error) {
|
|
69
|
+
failures.push(error instanceof Error ? error : new Error(String(error)));
|
|
70
|
+
failedNames.add(name);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { entries, failures, isFailed: (api) => failedNames.has(api.name) };
|
|
74
|
+
},
|
|
75
|
+
keyOf: (api) => `${api.host}/${api.name}`,
|
|
76
|
+
fingerprint: (api) => JSON.stringify(api),
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
onUp: (api) => console.log('up', api.name, api.url),
|
|
80
|
+
onDown: (api) => console.log('down', api.name),
|
|
81
|
+
onError: (error) => console.warn(error instanceof DiscoveryError ? error.source : '', error.message),
|
|
82
|
+
},
|
|
83
|
+
);
|
|
84
|
+
await watch.stop();
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
- A `readHost` that rejects is reported through `onError` and leaves that host's known entries in place.
|
|
88
|
+
- A `readHost` that resolves replaces them: an entry missing from `entries` is reported down, unless `isFailed` says it is one that failed this time. That one stays known until it fails `entryFailureLimit` reads in a row (3), and a successful read starts the count again.
|
|
89
|
+
- Identify the entries in `isFailed` by something known without reading them, such as the URL each was read from.
|
|
90
|
+
- `fingerprint` must cover everything a caller can see, because an unchanged fingerprint reports nothing.
|
|
91
|
+
- An `onUp` or `onDown` that throws is reported through `onError`, and the other entries are still reported. A promise it returns isn't awaited, so catch inside an async handler.
|
|
92
|
+
- `createEntryTracker` is the same logic without mDNS, driven by `hostUp` and `hostDown`, for tests or another source of hosts.
|
|
93
|
+
|
|
94
|
+
A process that also advertises sees itself; skip its own instance name. Anything on the LAN can advertise, so decide what to connect to by policy, not by name.
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# Serving a document
|
|
2
|
+
|
|
3
|
+
Serve a public JSON discovery document over HTTP with open CORS, a cache lifetime, an ETag and `304`. Pick the function by what you already have: a Node or Express app, a handler that chose to answer, or no Node server at all.
|
|
4
|
+
|
|
5
|
+
## In an app, beside other routes
|
|
6
|
+
|
|
7
|
+
`answeringMiddleware` answers the requests it owns and passes the rest to `next`. Check the path yourself with `requestPath`, which drops the query string.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { answeringMiddleware, documentHandler, requestOrigin, requestPath } from '@cubicecho/discovery-core';
|
|
11
|
+
|
|
12
|
+
const PATH = '/.well-known/example.json';
|
|
13
|
+
|
|
14
|
+
const serve = documentHandler('application/json', (request) => ({
|
|
15
|
+
specVersion: '1.0',
|
|
16
|
+
url: `${requestOrigin(request)}/api`,
|
|
17
|
+
}));
|
|
18
|
+
|
|
19
|
+
export const exampleDiscovery = answeringMiddleware(async (request, response) => {
|
|
20
|
+
const isMine = requestPath(request) === PATH;
|
|
21
|
+
if (isMine) {
|
|
22
|
+
await serve(request, response);
|
|
23
|
+
}
|
|
24
|
+
return isMine;
|
|
25
|
+
});
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Mount it with `app.use(exampleDiscovery)`. Several of these can share an app in any order, as long as each answers only its own path. An error thrown by the document source goes to `next(error)`.
|
|
29
|
+
|
|
30
|
+
The source runs on every request, so it can follow configuration that changes while the process runs.
|
|
31
|
+
|
|
32
|
+
## Without a path check
|
|
33
|
+
|
|
34
|
+
`documentHandler` checks no path and answers every request it is given. Use it bare only on a route that already matched:
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { documentHandler } from '@cubicecho/discovery-core';
|
|
38
|
+
|
|
39
|
+
const handler = documentHandler('application/json', () => ({ specVersion: '1.0' }), { maxAgeSeconds: 60 });
|
|
40
|
+
// Express 5: app.all('/.well-known/example.json', handler);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Use `app.all`, not `app.get`, so the handler also answers `OPTIONS` and `405`. `writeDocument(request, response, document, mediaType)` does the same for a document you already hold.
|
|
44
|
+
|
|
45
|
+
## Without a Node server
|
|
46
|
+
|
|
47
|
+
`documentResponse` works out the status, headers and body for any framework:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { documentResponse } from '@cubicecho/discovery-core';
|
|
51
|
+
|
|
52
|
+
export function fetchHandler(request: Request): Response {
|
|
53
|
+
const { status, headers, body } = documentResponse({ specVersion: '1.0' }, 'application/json', {
|
|
54
|
+
method: request.method,
|
|
55
|
+
ifNoneMatch: request.headers.get('if-none-match') ?? undefined,
|
|
56
|
+
});
|
|
57
|
+
return new Response(body === '' ? null : body, { status, headers });
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
It answers `GET` and `HEAD` with the document, `OPTIONS` with `204`, and any other method with `405`. The body is empty for `HEAD`, `OPTIONS`, `304` and `405`.
|
|
62
|
+
|
|
63
|
+
## URLs inside the document
|
|
64
|
+
|
|
65
|
+
`requestOrigin(request)` is the `scheme://host[:port]` the client used, from its `Host` header. It throws when there is no `Host` header, and it reads the scheme from the socket, so it says `http` behind a TLS-terminating proxy. See [common mistakes](common-mistakes.md#using-requestorigin-behind-a-tls-terminating-proxy).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# TXT records
|
|
2
|
+
|
|
3
|
+
Write and read the TXT record of an advertised service the way every discovery package here does: a layout version, an explicit TLS flag, and paths that can't point at another host.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { assertLocalPaths, FLAG_ON, readTxtFlag, readTxtPath, TXT_TLS_KEY, TXT_VERSION_KEY } from '@cubicecho/discovery-core/mdns';
|
|
7
|
+
|
|
8
|
+
const DEFAULT_PATH = '/api';
|
|
9
|
+
|
|
10
|
+
export function buildTxt(path: string, tls: boolean): Record<string, string> {
|
|
11
|
+
assertLocalPaths([path]);
|
|
12
|
+
return { [TXT_VERSION_KEY]: '1', path, ...(tls ? { [TXT_TLS_KEY]: FLAG_ON } : {}) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseTxt(txt: Readonly<Record<string, unknown>> | undefined) {
|
|
16
|
+
return { path: readTxtPath(txt, 'path', DEFAULT_PATH), tls: readTxtFlag(txt, TXT_TLS_KEY) };
|
|
17
|
+
}
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
- **Version.** Put `txtvers` in every record.
|
|
21
|
+
- **Flags.** On is the string `'1'` (`FLAG_ON`); off is a missing key. `readTxtFlag` is false for anything else, including `'true'`.
|
|
22
|
+
- **Paths.** `assertLocalPaths` throws unless each path starts with a single `/`. On the reading side the record is untrusted, so `readTxtPath` answers the fallback for a missing or unsafe value (`//evil/x`, `http://…`).
|
|
File without changes
|
|
File without changes
|
package/dist/core/defaults.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export interface MdnsSettings {
|
|
|
22
22
|
announceTimeoutMs: number;
|
|
23
23
|
/** How often an entry watch re-reads every known host's document, to catch entries added or removed, in ms. */
|
|
24
24
|
refreshMs: number;
|
|
25
|
+
/** How many reads in a row an entry may fail before it is reported down; 1 reports it on the first. */
|
|
26
|
+
entryFailureLimit: number;
|
|
25
27
|
}
|
|
26
28
|
/** The mDNS defaults; probing alone takes about 750 ms. */
|
|
27
29
|
export declare const MDNS_DEFAULTS: Readonly<MdnsSettings>;
|
package/dist/core/defaults.js
CHANGED
package/dist/core/errors.d.ts
CHANGED
|
File without changes
|
package/dist/core/errors.js
CHANGED
|
File without changes
|
package/dist/core/host-slug.d.ts
CHANGED
|
File without changes
|
package/dist/core/host-slug.js
CHANGED
|
File without changes
|
package/dist/core/parse.d.ts
CHANGED
|
File without changes
|
package/dist/core/parse.js
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/dist/index.d.ts
CHANGED
|
File without changes
|
package/dist/index.js
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/dist/mdns/advertiser.js
CHANGED
|
File without changes
|
package/dist/mdns/browse.d.ts
CHANGED
|
File without changes
|
package/dist/mdns/browse.js
CHANGED
|
File without changes
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Kept apart from mDNS so it can be driven, and tested, by anything that reports hosts.
|
|
6
6
|
*/
|
|
7
|
+
import { type MdnsSettings } from '../core/defaults.ts';
|
|
7
8
|
/**
|
|
8
9
|
* What one read of a host's document gave.
|
|
9
10
|
*
|
|
@@ -14,6 +15,11 @@ export interface HostRead<E> {
|
|
|
14
15
|
entries: E[];
|
|
15
16
|
/** Every entry that could not be read; reported through `onError`, and the rest still count. */
|
|
16
17
|
failures: Error[];
|
|
18
|
+
/**
|
|
19
|
+
* Whether a known entry is one that failed this time, rather than one the document stopped listing. Such an
|
|
20
|
+
* entry stays known until it fails `entryFailureLimit` reads in a row. Unset, it is reported down at once.
|
|
21
|
+
*/
|
|
22
|
+
isFailed?: (entry: E) => boolean;
|
|
17
23
|
}
|
|
18
24
|
/**
|
|
19
25
|
* What an entry watch tells its caller.
|
|
@@ -23,9 +29,9 @@ export interface HostRead<E> {
|
|
|
23
29
|
export interface EntryWatchHandlers<E> {
|
|
24
30
|
/** An entry appeared, or changed. */
|
|
25
31
|
onUp: (entry: E) => void;
|
|
26
|
-
/** An entry's host left,
|
|
32
|
+
/** An entry's host left, its document stopped listing it, or it failed too many reads in a row. */
|
|
27
33
|
onDown?: (entry: E) => void;
|
|
28
|
-
/** A document or entry could not be read, or a socket failed;
|
|
34
|
+
/** A document or entry could not be read, a handler threw, or a socket failed; process warnings when unset. */
|
|
29
35
|
onError?: (error: Error) => void;
|
|
30
36
|
}
|
|
31
37
|
/**
|
|
@@ -69,8 +75,9 @@ export interface EntryTracker<H, E> {
|
|
|
69
75
|
* @typeParam E - What the host lists.
|
|
70
76
|
* @param handlers - Told about entries coming, changing and going, and about errors.
|
|
71
77
|
* @param source - Reads a host, and keys and fingerprints entries.
|
|
78
|
+
* @param [overrides] - mDNS settings to change; `entryFailureLimit` is how many failed reads in a row an entry survives.
|
|
72
79
|
* @returns The tracker.
|
|
73
80
|
*/
|
|
74
81
|
export declare function createEntryTracker<H extends {
|
|
75
82
|
name: string;
|
|
76
|
-
}, E>(handlers: EntryWatchHandlers<E>, source: EntrySource<H, E>): EntryTracker<H, E>;
|
|
83
|
+
}, E>(handlers: EntryWatchHandlers<E>, source: EntrySource<H, E>, overrides?: Partial<MdnsSettings>): EntryTracker<H, E>;
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Kept apart from mDNS so it can be driven, and tested, by anything that reports hosts.
|
|
6
6
|
*/
|
|
7
|
+
import { MDNS_DEFAULTS } from '../core/defaults.js';
|
|
7
8
|
import { errorReporter } from './report-error.js';
|
|
8
9
|
/**
|
|
9
10
|
* A tracker that reports entries through `handlers`.
|
|
@@ -12,17 +13,30 @@ import { errorReporter } from './report-error.js';
|
|
|
12
13
|
* @typeParam E - What the host lists.
|
|
13
14
|
* @param handlers - Told about entries coming, changing and going, and about errors.
|
|
14
15
|
* @param source - Reads a host, and keys and fingerprints entries.
|
|
16
|
+
* @param [overrides] - mDNS settings to change; `entryFailureLimit` is how many failed reads in a row an entry survives.
|
|
15
17
|
* @returns The tracker.
|
|
16
18
|
*/
|
|
17
|
-
export function createEntryTracker(handlers, source) {
|
|
19
|
+
export function createEntryTracker(handlers, source, overrides = {}) {
|
|
20
|
+
const { entryFailureLimit } = { ...MDNS_DEFAULTS, ...overrides };
|
|
18
21
|
const report = errorReporter(handlers.onError);
|
|
19
22
|
/** The latest record of each host, by instance name. */
|
|
20
23
|
const hosts = new Map();
|
|
21
24
|
/** Each host's entries, by key. */
|
|
22
25
|
const known = new Map();
|
|
26
|
+
/** How many reads in a row each host's kept entries have failed, by key. */
|
|
27
|
+
const failed = new Map();
|
|
23
28
|
/** Each host's last read, so two reads of one host never overlap. */
|
|
24
29
|
const reads = new Map();
|
|
25
30
|
let isClosed = false;
|
|
31
|
+
/** Calls a caller's handler; one that throws is reported, so it can't cost the other entries their reports. */
|
|
32
|
+
const notify = (handler, entry) => {
|
|
33
|
+
try {
|
|
34
|
+
handler?.(entry);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
report(error instanceof Error ? error : new Error(String(error)));
|
|
38
|
+
}
|
|
39
|
+
};
|
|
26
40
|
const sync = async (host) => {
|
|
27
41
|
let read;
|
|
28
42
|
try {
|
|
@@ -44,23 +58,36 @@ export function createEntryTracker(handlers, source) {
|
|
|
44
58
|
next.set(source.keyOf(entry), entry);
|
|
45
59
|
}
|
|
46
60
|
const previous = known.get(host.name) ?? new Map();
|
|
61
|
+
const failedBefore = failed.get(host.name) ?? new Map();
|
|
62
|
+
const failedNow = new Map();
|
|
63
|
+
for (const [key, entry] of previous) {
|
|
64
|
+
const hasFailed = next.has(key) === false && read.isFailed?.(entry) === true;
|
|
65
|
+
const count = (failedBefore.get(key) ?? 0) + 1;
|
|
66
|
+
if (hasFailed && count < entryFailureLimit) {
|
|
67
|
+
failedNow.set(key, count);
|
|
68
|
+
next.set(key, entry);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
failed.set(host.name, failedNow);
|
|
47
72
|
known.set(host.name, next);
|
|
48
73
|
for (const [key, entry] of previous) {
|
|
49
74
|
if (next.has(key) === false) {
|
|
50
|
-
handlers.onDown
|
|
75
|
+
notify(handlers.onDown, entry);
|
|
51
76
|
}
|
|
52
77
|
}
|
|
53
78
|
for (const [key, entry] of next) {
|
|
54
79
|
const before = previous.get(key);
|
|
55
80
|
const isNewOrChanged = before === undefined || source.fingerprint(before) !== source.fingerprint(entry);
|
|
56
81
|
if (isNewOrChanged) {
|
|
57
|
-
handlers.onUp
|
|
82
|
+
notify(handlers.onUp, entry);
|
|
58
83
|
}
|
|
59
84
|
}
|
|
60
85
|
};
|
|
61
86
|
const hostUp = (host) => {
|
|
62
87
|
hosts.set(host.name, host);
|
|
63
|
-
const
|
|
88
|
+
const readNext = () => sync(host);
|
|
89
|
+
// Runs whether or not the last read rejected, so one failure can't stop every later read.
|
|
90
|
+
const read = (reads.get(host.name) ?? Promise.resolve()).then(readNext, readNext);
|
|
64
91
|
reads.set(host.name, read);
|
|
65
92
|
return read;
|
|
66
93
|
};
|
|
@@ -68,11 +95,12 @@ export function createEntryTracker(handlers, source) {
|
|
|
68
95
|
hosts.delete(host.name);
|
|
69
96
|
const entries = known.get(host.name) ?? new Map();
|
|
70
97
|
known.delete(host.name);
|
|
98
|
+
failed.delete(host.name);
|
|
71
99
|
if (isClosed) {
|
|
72
100
|
return;
|
|
73
101
|
}
|
|
74
102
|
for (const entry of entries.values()) {
|
|
75
|
-
handlers.onDown
|
|
103
|
+
notify(handlers.onDown, entry);
|
|
76
104
|
}
|
|
77
105
|
};
|
|
78
106
|
return {
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/dist/mdns/responder.d.ts
CHANGED
|
File without changes
|
package/dist/mdns/responder.js
CHANGED
|
File without changes
|
package/dist/mdns/txt.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export declare const FLAG_ON = "1";
|
|
|
11
11
|
* Whether a value from the network is safe to resolve against the host as a path.
|
|
12
12
|
*
|
|
13
13
|
* @param value - A TXT value.
|
|
14
|
-
* @returns true for an absolute path; false for anything else, including `//other-host/…`.
|
|
14
|
+
* @returns true for an absolute path; false for anything else, including what a URL parser reads as `//other-host/…`.
|
|
15
15
|
*/
|
|
16
16
|
export declare function isLocalPath(value: unknown): value is string;
|
|
17
17
|
/**
|
package/dist/mdns/txt.js
CHANGED
|
@@ -7,14 +7,19 @@ export const TXT_VERSION_KEY = 'txtvers';
|
|
|
7
7
|
export const TXT_TLS_KEY = 'tls';
|
|
8
8
|
/** The value a flag key carries when it is on; a bare key does not survive bonjour-service's decoding. */
|
|
9
9
|
export const FLAG_ON = '1';
|
|
10
|
+
/**
|
|
11
|
+
* A path URL parsing keeps on the host it is resolved against: one leading `/`, and none of the characters
|
|
12
|
+
* the parser reads as another one (a backslash) or drops (tab, newline, carriage return).
|
|
13
|
+
*/
|
|
14
|
+
const LOCAL_PATH_PATTERN = /^\/(?!\/)[^\\\t\n\r]*$/;
|
|
10
15
|
/**
|
|
11
16
|
* Whether a value from the network is safe to resolve against the host as a path.
|
|
12
17
|
*
|
|
13
18
|
* @param value - A TXT value.
|
|
14
|
-
* @returns true for an absolute path; false for anything else, including `//other-host/…`.
|
|
19
|
+
* @returns true for an absolute path; false for anything else, including what a URL parser reads as `//other-host/…`.
|
|
15
20
|
*/
|
|
16
21
|
export function isLocalPath(value) {
|
|
17
|
-
return typeof value === 'string' &&
|
|
22
|
+
return typeof value === 'string' && LOCAL_PATH_PATTERN.test(value);
|
|
18
23
|
}
|
|
19
24
|
/**
|
|
20
25
|
* Checks paths about to be advertised, since a client resolves each one against the host.
|
|
@@ -25,7 +30,7 @@ export function isLocalPath(value) {
|
|
|
25
30
|
export function assertLocalPaths(paths) {
|
|
26
31
|
for (const path of paths) {
|
|
27
32
|
if (isLocalPath(path) === false) {
|
|
28
|
-
throw new Error(`An advertised path starts with a single "/"; got "${path}"`);
|
|
33
|
+
throw new Error(`An advertised path starts with a single "/" and has no backslash, tab or line break; got "${path}"`);
|
|
29
34
|
}
|
|
30
35
|
}
|
|
31
36
|
}
|
|
@@ -25,7 +25,8 @@ export interface EntryWatch<E> {
|
|
|
25
25
|
* @param browse - The service type, and how to read a found service.
|
|
26
26
|
* @param source - Reads a host's document, and keys and fingerprints entries.
|
|
27
27
|
* @param handlers - Told about entries and errors.
|
|
28
|
-
* @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read
|
|
28
|
+
* @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read, and `entryFailureLimit` how many failed
|
|
29
|
+
* reads in a row an entry survives.
|
|
29
30
|
* @returns The watch, to stop when done.
|
|
30
31
|
* @throws If bonjour-service is not installed.
|
|
31
32
|
*
|
|
@@ -12,7 +12,8 @@ import { createEntryTracker } from './entry-tracker.js';
|
|
|
12
12
|
* @param browse - The service type, and how to read a found service.
|
|
13
13
|
* @param source - Reads a host's document, and keys and fingerprints entries.
|
|
14
14
|
* @param handlers - Told about entries and errors.
|
|
15
|
-
* @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read
|
|
15
|
+
* @param [overrides] - mDNS settings to change; `refreshMs` is how often documents are re-read, and `entryFailureLimit` how many failed
|
|
16
|
+
* reads in a row an entry survives.
|
|
16
17
|
* @returns The watch, to stop when done.
|
|
17
18
|
* @throws If bonjour-service is not installed.
|
|
18
19
|
*
|
|
@@ -22,7 +23,7 @@ import { createEntryTracker } from './entry-tracker.js';
|
|
|
22
23
|
*/
|
|
23
24
|
export async function watchEntries(browse, source, handlers, overrides = {}) {
|
|
24
25
|
const { refreshMs } = { ...MDNS_DEFAULTS, ...overrides };
|
|
25
|
-
const tracker = createEntryTracker(handlers, source);
|
|
26
|
+
const tracker = createEntryTracker(handlers, source, overrides);
|
|
26
27
|
const serviceWatch = await watchServices(browse, {
|
|
27
28
|
// hostUp reports a document that can't be read through onError rather than rejecting.
|
|
28
29
|
onUp: (host) => void tracker.hostUp(host),
|
package/dist/mdns.d.ts
CHANGED
|
File without changes
|
package/dist/mdns.js
CHANGED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
package/llms.txt
CHANGED
|
@@ -2,73 +2,85 @@
|
|
|
2
2
|
|
|
3
3
|
> The shared core of the cubicecho discovery packages: serving and fetching public discovery documents, and mDNS advertising and browsing on one responder per process.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
Requires Node >=22
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
Fetching a discovery document from a host nobody has vetted
|
|
15
|
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
- `
|
|
25
|
-
- `
|
|
26
|
-
- `
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
- `
|
|
31
|
-
- `
|
|
32
|
-
- `
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
- `
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
- `
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
- `
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
- `
|
|
55
|
-
- `
|
|
56
|
-
- `
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
- `
|
|
63
|
-
- `
|
|
64
|
-
- `
|
|
65
|
-
- `
|
|
66
|
-
- `
|
|
67
|
-
- `
|
|
68
|
-
- `
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
- `
|
|
5
|
+
Agent-facing docs for @cubicecho/discovery-core: one task or concept per page, then what each package.json "exports" entry exports. Generated from _agents/docs/ and the doc comments in src/ by @cubicecho/agent-docs; edit those, not this file.
|
|
6
|
+
|
|
7
|
+
Requires Node >=22. Peer dependencies: `bonjour-service` >=1.4 (optional), `zod` >=4.1.
|
|
8
|
+
|
|
9
|
+
## Docs
|
|
10
|
+
|
|
11
|
+
- [Install and entry points](_agents/docs/01-install.md): How to depend on `@cubicecho/discovery-core` from a discovery package, which of its two entry points to import, and when `bonjour-service` is needed. An app that only wants to be found installs `@cubicecho/mcp-discovery` or `@cubicecho/graphql-mdns-discovery` instead.
|
|
12
|
+
- [Building a discovery package](_agents/docs/building-on-core.md): The rules a package built on `@cubicecho/discovery-core` follows so that an app can use it beside the other discovery packages without clashes.
|
|
13
|
+
- [Common mistakes](_agents/docs/common-mistakes.md): Mistakes that compile and mostly fail silently when building on `@cubicecho/discovery-core`, each with what happens and the fix.
|
|
14
|
+
- [Fetching a document](_agents/docs/fetching-documents.md): Fetch and validate a discovery document from a host nobody has vetted, bounded in time and size, and tell the failures apart.
|
|
15
|
+
- [Advertising on the LAN](_agents/docs/mdns-advertising.md): Announce a DNS-SD service over mDNS, keep the announcement in step with a live setting, and share one responder across everything in the process.
|
|
16
|
+
- [Browsing the LAN](_agents/docs/mdns-browsing.md): Find hosts advertising a DNS-SD service type, once or continuously, and turn those hosts into the entries their documents list.
|
|
17
|
+
- [Serving a document](_agents/docs/serving-documents.md): Serve a public JSON discovery document over HTTP with open CORS, a cache lifetime, an ETag and `304`. Pick the function by what you already have: a Node or Express app, a handler that chose to answer, or no Node server at all.
|
|
18
|
+
- [TXT records](_agents/docs/txt-records.md): Write and read the TXT record of an advertised service the way every discovery package here does: a layout version, an explicit TLS flag, and paths that can't point at another host.
|
|
19
|
+
|
|
20
|
+
## Exports: @cubicecho/discovery-core
|
|
21
|
+
|
|
22
|
+
The parts every cubicecho discovery package shares.
|
|
23
|
+
|
|
24
|
+
- `FetchOptions` (type): What every document fetch accepts besides its settings.
|
|
25
|
+
- `fetchJson`: Fetches a URL and parses its body as JSON, bounded in time and size.
|
|
26
|
+
- `FETCH_DEFAULTS`: The fetching defaults.
|
|
27
|
+
- `FetchSettings` (type): How discovery documents are fetched.
|
|
28
|
+
- `MDNS_DEFAULTS`: The mDNS defaults; probing alone takes about 750 ms.
|
|
29
|
+
- `MdnsSettings` (type): How mDNS advertising and browsing behave.
|
|
30
|
+
- `SERVE_DEFAULTS`: The serving defaults; the max age is the one the MCP Server Card spec recommends.
|
|
31
|
+
- `ServeSettings` (type): How discovery documents are served.
|
|
32
|
+
- `DiscoveryError`: Any failure to read a discovery document; discovery functions report these per entry.
|
|
33
|
+
- `DocumentFetchError`: A document could not be fetched: network failure, timeout, an error status or an oversized body.
|
|
34
|
+
- `InvalidDocumentError`: A document arrived but is not valid JSON, or does not match its schema.
|
|
35
|
+
- `hostSlug`: A hostname's first label as a slug: lowercase letters, digits and dashes, as a reverse-DNS name's namespace allows.
|
|
36
|
+
- `parseDocument`: Validates a document against its schema.
|
|
37
|
+
- `specVersionSchema`: A schema for a document's `specVersion` that accepts any minor of one major.
|
|
38
|
+
- `DocumentRequest` (type): The parts of a request that decide the response.
|
|
39
|
+
- `DocumentResponse` (type): A response ready to write to any server.
|
|
40
|
+
- `documentResponse`: Works out the response to a request for a discovery document.
|
|
41
|
+
- `answeringMiddleware`: Turns an "answer if it is mine" function into middleware.
|
|
42
|
+
- `DocumentHandler` (type): A Node request handler; it rejects when the document source throws.
|
|
43
|
+
- `DocumentMiddleware` (type): Express-style middleware: it answers the requests it owns and passes every other request to `next`.
|
|
44
|
+
- `DocumentSource` (type): Where a handler gets the document it serves, asked once per request so it can follow config changes.
|
|
45
|
+
- `documentHandler`: A handler that serves one kind of discovery document.
|
|
46
|
+
- `requestPath`: The path a request asks for, without its query string.
|
|
47
|
+
- `writeDocument`: Writes a discovery document as the response to a request.
|
|
48
|
+
- `requestOrigin`: The `scheme://host[:port]` a request was addressed to, from its `Host` header.
|
|
49
|
+
|
|
50
|
+
## Exports: @cubicecho/discovery-core/mdns
|
|
51
|
+
|
|
52
|
+
LAN advertising and browsing over mDNS / DNS-SD, for any service type, on one responder per process.
|
|
53
|
+
|
|
54
|
+
- `AdvertiseError`: The announcement did not go out in time, most often because the name is already in use on the network.
|
|
55
|
+
- `Advertisement` (type): A running advertisement.
|
|
56
|
+
- `advertiseService`: Advertises a DNS-SD service, resolving once the announcement has gone out.
|
|
57
|
+
- `ServiceAnnouncement` (type): One service to advertise.
|
|
58
|
+
- `Advertiser` (type): Keeps the announcement in step with `isWanted()`.
|
|
59
|
+
- `AdvertiserDeps` (type): What the advertiser needs from its host.
|
|
60
|
+
- `AdvertiserOptions` (type): What every advertiser's options carry, whatever the service type.
|
|
61
|
+
- `createAdvertiser`: An advertiser that announces nothing until the first `sync`.
|
|
62
|
+
- `FoundHost` (type): A host found on the network: where it is, and what its TXT record said.
|
|
63
|
+
- `FoundService` (type): What a found service has that a host reader reads.
|
|
64
|
+
- `findServices`: Listens for one service type for a while, then lists what answered.
|
|
65
|
+
- `ServiceBrowse` (type): What to browse for, and how to read what is found.
|
|
66
|
+
- `ServiceWatch` (type): A running watch.
|
|
67
|
+
- `ServiceWatchHandlers` (type): What a service watch tells its caller.
|
|
68
|
+
- `toFoundHost`: Turns a found service into a host, given how to read its TXT record.
|
|
69
|
+
- `watchServices`: Browses for one service type until stopped, reporting each host as it comes and goes.
|
|
70
|
+
- `createEntryTracker`: A tracker that reports entries through `handlers`.
|
|
71
|
+
- `EntrySource` (type): How the tracker reads hosts and tells entries apart.
|
|
72
|
+
- `EntryTracker` (type): Tracks the entries on a set of hosts.
|
|
73
|
+
- `EntryWatchHandlers` (type): What an entry watch tells its caller.
|
|
74
|
+
- `HostRead` (type): What one read of a host's document gave.
|
|
75
|
+
- `acquireResponder`: Opens the shared responder, or joins the one already open.
|
|
76
|
+
- `ResponderLease` (type): A hold on the shared responder; release it when done.
|
|
77
|
+
- `responderHolders`: How many leases the shared responder has open, for tests and diagnostics.
|
|
78
|
+
- `assertLocalPaths`: Checks paths about to be advertised, since a client resolves each one against the host.
|
|
79
|
+
- `FLAG_ON`: The value a flag key carries when it is on; a bare key does not survive bonjour-service's decoding.
|
|
80
|
+
- `isLocalPath`: Whether a value from the network is safe to resolve against the host as a path.
|
|
81
|
+
- `readTxtFlag`: Reads a flag from a TXT record.
|
|
82
|
+
- `readTxtPath`: Reads a path from a TXT record, falling back when it is missing or unsafe.
|
|
83
|
+
- `TXT_TLS_KEY`: The key present, set to FLAG_ON, when the advertised host speaks HTTPS.
|
|
84
|
+
- `TXT_VERSION_KEY`: The key that carries a record's layout version.
|
|
85
|
+
- `EntryWatch` (type): A running entry watch.
|
|
86
|
+
- `watchEntries`: Watches the network for the entries hosts of one service type list, reporting each as it appears, changes and goes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cubicecho/discovery-core",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "The shared core of the cubicecho discovery packages: serving and fetching public discovery documents, and mDNS advertising and browsing on one responder per process.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"discovery",
|
|
@@ -36,26 +36,27 @@
|
|
|
36
36
|
},
|
|
37
37
|
"files": [
|
|
38
38
|
"dist",
|
|
39
|
-
"llms.txt"
|
|
39
|
+
"llms.txt",
|
|
40
|
+
"_agents/docs"
|
|
40
41
|
],
|
|
41
42
|
"publishConfig": {
|
|
42
43
|
"access": "public"
|
|
43
44
|
},
|
|
44
45
|
"scripts": {
|
|
45
|
-
"build": "tsc -p tsconfig.build.json
|
|
46
|
-
"prepack": "npm run build",
|
|
46
|
+
"build": "tsc -p tsconfig.build.json",
|
|
47
|
+
"prepack": "npm run build && agent-docs llms",
|
|
47
48
|
"check": "npm run check:biome && npm run check:types",
|
|
48
49
|
"check:biome": "biome check --write .",
|
|
49
50
|
"check:types": "tsc --noEmit",
|
|
50
51
|
"test": "vitest run",
|
|
51
52
|
"test:watch": "vitest",
|
|
52
|
-
"llms": "
|
|
53
|
-
"
|
|
54
|
-
"
|
|
53
|
+
"llms": "agent-docs llms",
|
|
54
|
+
"coverage": "vitest run --coverage",
|
|
55
|
+
"docs:check": "agent-docs check"
|
|
55
56
|
},
|
|
56
57
|
"peerDependencies": {
|
|
57
|
-
"
|
|
58
|
-
"
|
|
58
|
+
"bonjour-service": ">=1.4",
|
|
59
|
+
"zod": ">=4.1"
|
|
59
60
|
},
|
|
60
61
|
"peerDependenciesMeta": {
|
|
61
62
|
"bonjour-service": {
|
|
@@ -64,6 +65,7 @@
|
|
|
64
65
|
},
|
|
65
66
|
"devDependencies": {
|
|
66
67
|
"@biomejs/biome": "2.5.12",
|
|
68
|
+
"@cubicecho/agent-docs": "^0.2.0",
|
|
67
69
|
"@semantic-release/changelog": "^7.0.0",
|
|
68
70
|
"@semantic-release/git": "^11.0.1",
|
|
69
71
|
"@types/node": "^26.6.6",
|