@treecrdt/discovery-server-node 0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Cybersemics Institute
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # TreeCRDT Discovery Server (Node)
2
+
3
+ Small standalone HTTP bootstrap service for `resolveDoc`.
4
+
5
+ It is intentionally separate from the websocket sync server:
6
+
7
+ - discovery/bootstrap happens once at connect time
8
+ - clients cache the returned attachment plan
9
+ - steady-state sync then talks directly to the resolved `ws://` or `wss://` endpoint
10
+
11
+ ## Run locally
12
+
13
+ From the repo root:
14
+
15
+ ```sh
16
+ pnpm discovery-server:local
17
+ ```
18
+
19
+ This starts a bootstrap server on `http://localhost:8788` that advertises:
20
+
21
+ - bootstrap base: `http://localhost:8788`
22
+ - sync websocket base: `ws://localhost:8787`
23
+
24
+ ## Environment
25
+
26
+ - `HOST` (default: `0.0.0.0`)
27
+ - `PORT` (default: `8788`)
28
+ - `TREECRDT_DISCOVERY_RESOLVE_PATH` (default: `/resolve-doc`)
29
+ - `TREECRDT_DISCOVERY_PUBLIC_HTTP_BASE_URL` (optional absolute HTTP base URL advertised to clients)
30
+ - `TREECRDT_DISCOVERY_PUBLIC_WS_BASE_URL` (optional absolute websocket base URL advertised to clients)
31
+ - `TREECRDT_DISCOVERY_CACHE_TTL_MS` (default: `3600000`)
32
+
33
+ ## Endpoints
34
+
35
+ - `GET /health`
36
+ - `GET /status`
37
+ - `GET /resolve-doc?docId=YOUR_DOC_ID`
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,74 @@
1
+ import fs from 'node:fs';
2
+ import { startDiscoveryServer } from './server.js';
3
+ function clientHostForBindHost(host) {
4
+ const trimmed = host.trim();
5
+ if (trimmed === '0.0.0.0' || trimmed === '::' || trimmed === '[::]') {
6
+ return 'localhost';
7
+ }
8
+ return trimmed;
9
+ }
10
+ function parseBooleanEnv(name, fallback) {
11
+ const raw = process.env[name];
12
+ if (!raw || raw.trim().length === 0)
13
+ return fallback;
14
+ const normalized = raw.trim().toLowerCase();
15
+ if (['1', 'true', 'yes', 'on'].includes(normalized))
16
+ return true;
17
+ if (['0', 'false', 'no', 'off'].includes(normalized))
18
+ return false;
19
+ throw new Error(`${name} must be a boolean (true/false), got: ${raw}`);
20
+ }
21
+ function readPackageVersion() {
22
+ try {
23
+ const packageJsonUrl = new URL('../package.json', import.meta.url);
24
+ const parsed = JSON.parse(fs.readFileSync(packageJsonUrl, 'utf8'));
25
+ return typeof parsed.version === 'string' && parsed.version.trim().length > 0
26
+ ? parsed.version.trim()
27
+ : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ async function main() {
34
+ const host = process.env.HOST ?? '0.0.0.0';
35
+ const port = Number(process.env.PORT ?? '8788');
36
+ const resolveDocPath = process.env.TREECRDT_DISCOVERY_RESOLVE_PATH?.trim() || undefined;
37
+ const publicHttpBaseUrl = process.env.TREECRDT_DISCOVERY_PUBLIC_HTTP_BASE_URL?.trim() || undefined;
38
+ const publicWebSocketBaseUrl = process.env.TREECRDT_DISCOVERY_PUBLIC_WS_BASE_URL?.trim() || undefined;
39
+ const cacheTtlMs = Number(process.env.TREECRDT_DISCOVERY_CACHE_TTL_MS ?? String(60 * 60 * 1000));
40
+ const packageVersion = readPackageVersion();
41
+ const gitSha = process.env.TREECRDT_DISCOVERY_GIT_SHA?.trim() || undefined;
42
+ const gitDirty = parseBooleanEnv('TREECRDT_DISCOVERY_GIT_DIRTY', false);
43
+ const startedAt = new Date().toISOString();
44
+ if (!Number.isFinite(port) || port <= 0)
45
+ throw new Error(`invalid PORT: ${process.env.PORT}`);
46
+ if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
47
+ throw new Error('invalid TREECRDT_DISCOVERY_CACHE_TTL_MS');
48
+ }
49
+ const handle = await startDiscoveryServer({
50
+ host,
51
+ port,
52
+ resolveDocPath,
53
+ publicHttpBaseUrl,
54
+ publicWebSocketBaseUrl,
55
+ cacheTtlMs,
56
+ packageVersion,
57
+ gitSha,
58
+ gitDirty,
59
+ startedAt,
60
+ });
61
+ const clientHost = clientHostForBindHost(handle.host);
62
+ console.log(`TreeCRDT discovery server listening on ${handle.host}:${handle.port}`);
63
+ console.log(`- bind: http://${handle.host}:${handle.port}`);
64
+ console.log(`- health: http://${clientHost}:${handle.port}/health`);
65
+ console.log(`- status: http://${clientHost}:${handle.port}/status`);
66
+ console.log(`- resolve: http://${clientHost}:${handle.port}${resolveDocPath ?? '/resolve-doc'}?docId=YOUR_DOC_ID`);
67
+ if (publicHttpBaseUrl || publicWebSocketBaseUrl) {
68
+ console.log(`- advertised endpoints: ${publicHttpBaseUrl ?? '(derived from request)'} / ${publicWebSocketBaseUrl ?? '(derived from request)'}`);
69
+ }
70
+ }
71
+ main().catch((err) => {
72
+ console.error(err);
73
+ process.exitCode = 1;
74
+ });
@@ -0,0 +1 @@
1
+ export * from './server.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './server.js';
@@ -0,0 +1,43 @@
1
+ import http from 'node:http';
2
+ import type { ResolveDocRequest, ResolveDocResponse } from '@treecrdt/discovery';
3
+ type Awaitable<T> = T | Promise<T>;
4
+ export type DiscoveryServerResolveContext = {
5
+ req: http.IncomingMessage;
6
+ url: URL;
7
+ };
8
+ export type DiscoveryServerResolveHandler = (request: ResolveDocRequest, ctx: DiscoveryServerResolveContext) => Awaitable<ResolveDocResponse>;
9
+ export type DiscoveryServerHealthResult = {
10
+ ok: true;
11
+ body?: string;
12
+ contentType?: string;
13
+ } | {
14
+ ok: false;
15
+ statusCode?: number;
16
+ body?: string;
17
+ contentType?: string;
18
+ };
19
+ export type DiscoveryServerOptions = {
20
+ host?: string;
21
+ port?: number;
22
+ healthPath?: string;
23
+ statusPath?: string;
24
+ resolveDocPath?: string;
25
+ publicHttpBaseUrl?: string;
26
+ publicWebSocketBaseUrl?: string;
27
+ cacheTtlMs?: number;
28
+ resolveDoc?: DiscoveryServerResolveHandler;
29
+ healthCheck?: () => Awaitable<DiscoveryServerHealthResult>;
30
+ statusInfo?: () => Awaitable<Record<string, unknown>>;
31
+ packageName?: string;
32
+ packageVersion?: string;
33
+ gitSha?: string;
34
+ gitDirty?: boolean;
35
+ startedAt?: string;
36
+ };
37
+ export type DiscoveryServerHandle = {
38
+ host: string;
39
+ port: number;
40
+ close: () => Promise<void>;
41
+ };
42
+ export declare function startDiscoveryServer(opts?: DiscoveryServerOptions): Promise<DiscoveryServerHandle>;
43
+ export {};
package/dist/server.js ADDED
@@ -0,0 +1,229 @@
1
+ import http from 'node:http';
2
+ function normalizeOptionalAbsoluteUrl(name, value, allowedProtocols) {
3
+ if (!value)
4
+ return undefined;
5
+ const trimmed = value.trim();
6
+ if (trimmed.length === 0)
7
+ return undefined;
8
+ let url;
9
+ try {
10
+ url = new URL(trimmed);
11
+ }
12
+ catch {
13
+ throw new Error(`${name} must be a valid absolute URL`);
14
+ }
15
+ if (!allowedProtocols.includes(url.protocol)) {
16
+ throw new Error(`${name} must use ${allowedProtocols.join(', ')}`);
17
+ }
18
+ return url.toString().replace(/\/$/, '');
19
+ }
20
+ function normalizePath(name, value, fallback) {
21
+ const trimmed = value?.trim() || fallback;
22
+ if (!trimmed.startsWith('/'))
23
+ throw new Error(`${name} must start with "/"`);
24
+ return trimmed;
25
+ }
26
+ function firstForwardedHeader(value) {
27
+ if (Array.isArray(value))
28
+ value = value[0];
29
+ if (!value)
30
+ return undefined;
31
+ const first = value.split(',')[0]?.trim();
32
+ return first && first.length > 0 ? first : undefined;
33
+ }
34
+ function derivePublicBaseUrl(req, fallbackProtocol) {
35
+ const host = firstForwardedHeader(req.headers['x-forwarded-host']) ?? req.headers.host ?? 'localhost';
36
+ const forwardedProto = firstForwardedHeader(req.headers['x-forwarded-proto']);
37
+ const protocol = forwardedProto && forwardedProto.length > 0
38
+ ? fallbackProtocol === 'ws'
39
+ ? forwardedProto === 'https'
40
+ ? 'wss'
41
+ : 'ws'
42
+ : forwardedProto
43
+ : fallbackProtocol;
44
+ return `${protocol}://${host}`.replace(/\/$/, '');
45
+ }
46
+ function buildDefaultResolveDocHandler(opts) {
47
+ return async (request, ctx) => {
48
+ const publicHttpBaseUrl = opts.publicHttpBaseUrl ?? derivePublicBaseUrl(ctx.req, 'http');
49
+ const publicWebSocketBaseUrl = opts.publicWebSocketBaseUrl ?? derivePublicBaseUrl(ctx.req, 'ws');
50
+ return {
51
+ docId: request.docId,
52
+ plan: {
53
+ topology: 'relay',
54
+ attachments: [
55
+ {
56
+ protocol: 'websocket',
57
+ role: 'preferred',
58
+ url: `${publicWebSocketBaseUrl}/sync`,
59
+ },
60
+ {
61
+ protocol: 'https',
62
+ role: 'bootstrap',
63
+ url: publicHttpBaseUrl,
64
+ },
65
+ ],
66
+ cacheTtlMs: opts.cacheTtlMs,
67
+ },
68
+ };
69
+ };
70
+ }
71
+ export async function startDiscoveryServer(opts = {}) {
72
+ const host = opts.host ?? '0.0.0.0';
73
+ const port = Number(opts.port ?? 8788);
74
+ const healthPath = normalizePath('healthPath', opts.healthPath, '/health');
75
+ const statusPath = normalizePath('statusPath', opts.statusPath, '/status');
76
+ const resolveDocPath = normalizePath('resolveDocPath', opts.resolveDocPath, '/resolve-doc');
77
+ const publicHttpBaseUrl = normalizeOptionalAbsoluteUrl('publicHttpBaseUrl', opts.publicHttpBaseUrl, ['http:', 'https:']);
78
+ const publicWebSocketBaseUrl = normalizeOptionalAbsoluteUrl('publicWebSocketBaseUrl', opts.publicWebSocketBaseUrl, ['ws:', 'wss:', 'http:', 'https:']);
79
+ const cacheTtlMs = opts.cacheTtlMs == null ? 60 * 60 * 1000 : Number(opts.cacheTtlMs);
80
+ const packageName = opts.packageName?.trim() || '@treecrdt/discovery-server-node';
81
+ const packageVersion = opts.packageVersion?.trim() || undefined;
82
+ const gitSha = opts.gitSha?.trim() || undefined;
83
+ const gitDirty = Boolean(opts.gitDirty);
84
+ const startedAt = opts.startedAt?.trim() || new Date().toISOString();
85
+ const startedAtMs = Date.parse(startedAt);
86
+ if (!Number.isFinite(port) || port < 0)
87
+ throw new Error(`invalid port: ${opts.port}`);
88
+ if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
89
+ throw new Error(`invalid cacheTtlMs: ${opts.cacheTtlMs}`);
90
+ }
91
+ const resolveDoc = opts.resolveDoc ??
92
+ buildDefaultResolveDocHandler({
93
+ publicHttpBaseUrl,
94
+ publicWebSocketBaseUrl,
95
+ cacheTtlMs,
96
+ });
97
+ const discoveryCorsHeaders = {
98
+ 'access-control-allow-origin': '*',
99
+ 'access-control-allow-methods': 'GET,OPTIONS',
100
+ 'access-control-allow-headers': 'content-type,authorization',
101
+ };
102
+ const server = http.createServer((req, res) => {
103
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
104
+ if (url.pathname === healthPath) {
105
+ void (async () => {
106
+ try {
107
+ const result = (await opts.healthCheck?.()) ?? { ok: true };
108
+ if (result.ok) {
109
+ res.writeHead(200, { 'content-type': result.contentType ?? 'text/plain' });
110
+ res.end(result.body ?? 'ok');
111
+ return;
112
+ }
113
+ const requestedStatusCode = result.statusCode;
114
+ const statusCode = typeof requestedStatusCode === 'number' &&
115
+ Number.isInteger(requestedStatusCode) &&
116
+ requestedStatusCode >= 400 &&
117
+ requestedStatusCode <= 599
118
+ ? requestedStatusCode
119
+ : 503;
120
+ res.writeHead(statusCode, { 'content-type': result.contentType ?? 'text/plain' });
121
+ res.end(result.body ?? 'not ready');
122
+ }
123
+ catch {
124
+ res.writeHead(503, { 'content-type': 'text/plain' });
125
+ res.end('not ready');
126
+ }
127
+ })();
128
+ return;
129
+ }
130
+ if (url.pathname === statusPath) {
131
+ void (async () => {
132
+ try {
133
+ const status = {
134
+ ok: true,
135
+ service: packageName,
136
+ version: packageVersion ?? null,
137
+ gitSha: gitSha ?? null,
138
+ gitDirty,
139
+ buildRef: gitSha ? `${gitSha}${gitDirty ? '-dirty' : ''}` : null,
140
+ startedAt,
141
+ uptimeMs: Number.isFinite(startedAtMs) ? Math.max(0, Date.now() - startedAtMs) : null,
142
+ resolveDocPath,
143
+ publicHttpBaseUrl: publicHttpBaseUrl ?? null,
144
+ publicWebSocketBaseUrl: publicWebSocketBaseUrl ?? null,
145
+ cacheTtlMs,
146
+ ...((await opts.statusInfo?.()) ?? {}),
147
+ };
148
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
149
+ res.end(JSON.stringify(status));
150
+ }
151
+ catch {
152
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
153
+ res.end(JSON.stringify({ ok: false, error: 'status unavailable' }));
154
+ }
155
+ })();
156
+ return;
157
+ }
158
+ if (url.pathname === resolveDocPath) {
159
+ void (async () => {
160
+ try {
161
+ if (req.method === 'OPTIONS') {
162
+ res.writeHead(204, discoveryCorsHeaders);
163
+ res.end();
164
+ return;
165
+ }
166
+ if (req.method && req.method !== 'GET') {
167
+ res.writeHead(405, {
168
+ 'content-type': 'application/json; charset=utf-8',
169
+ ...discoveryCorsHeaders,
170
+ });
171
+ res.end(JSON.stringify({ ok: false, error: 'method not allowed' }));
172
+ return;
173
+ }
174
+ const docId = url.searchParams.get('docId')?.trim();
175
+ if (!docId) {
176
+ res.writeHead(400, {
177
+ 'content-type': 'application/json; charset=utf-8',
178
+ ...discoveryCorsHeaders,
179
+ });
180
+ res.end(JSON.stringify({ ok: false, error: 'missing docId' }));
181
+ return;
182
+ }
183
+ const response = await resolveDoc({ docId }, { req, url });
184
+ res.writeHead(200, {
185
+ 'content-type': 'application/json; charset=utf-8',
186
+ ...discoveryCorsHeaders,
187
+ });
188
+ res.end(JSON.stringify(response));
189
+ }
190
+ catch {
191
+ res.writeHead(500, {
192
+ 'content-type': 'application/json; charset=utf-8',
193
+ ...discoveryCorsHeaders,
194
+ });
195
+ res.end(JSON.stringify({ ok: false, error: 'resolve failed' }));
196
+ }
197
+ })();
198
+ return;
199
+ }
200
+ res.writeHead(404, { 'content-type': 'text/plain' });
201
+ res.end('not found');
202
+ });
203
+ await new Promise((resolve, reject) => {
204
+ const onError = (error) => {
205
+ server.off('listening', onListening);
206
+ reject(error);
207
+ };
208
+ const onListening = () => {
209
+ server.off('error', onError);
210
+ resolve();
211
+ };
212
+ server.once('error', onError);
213
+ server.once('listening', onListening);
214
+ server.listen(port, host);
215
+ });
216
+ const address = server.address();
217
+ if (!address || typeof address === 'string') {
218
+ throw new Error('failed to start discovery server');
219
+ }
220
+ return {
221
+ host: address.address,
222
+ port: address.port,
223
+ close: async () => {
224
+ await new Promise((resolve, reject) => {
225
+ server.close((err) => (err ? reject(err) : resolve()));
226
+ });
227
+ },
228
+ };
229
+ }
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@treecrdt/discovery-server-node",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "import": "./dist/index.js",
10
+ "types": "./dist/index.d.ts"
11
+ }
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "src",
16
+ "README.md"
17
+ ],
18
+ "dependencies": {
19
+ "@treecrdt/discovery": "0.1.0"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^20.19.25",
23
+ "tsx": "^4.19.2",
24
+ "typescript": "^5.9.3",
25
+ "vitest": "^1.6.0"
26
+ },
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/cybersemics/treecrdt.git",
31
+ "directory": "packages/discovery-server-node"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/cybersemics/treecrdt/issues"
35
+ },
36
+ "homepage": "https://github.com/cybersemics/treecrdt#readme",
37
+ "publishConfig": {
38
+ "access": "public"
39
+ },
40
+ "scripts": {
41
+ "dev": "pnpm --filter @treecrdt/discovery-server-node^... run build && tsx src/cli.ts",
42
+ "build": "tsc -p tsconfig.json",
43
+ "test": "pnpm -C ../discovery run build && pnpm run build && vitest run"
44
+ }
45
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,85 @@
1
+ import fs from 'node:fs';
2
+
3
+ import { startDiscoveryServer } from './server.js';
4
+
5
+ function clientHostForBindHost(host: string): string {
6
+ const trimmed = host.trim();
7
+ if (trimmed === '0.0.0.0' || trimmed === '::' || trimmed === '[::]') {
8
+ return 'localhost';
9
+ }
10
+ return trimmed;
11
+ }
12
+
13
+ function parseBooleanEnv(name: string, fallback: boolean): boolean {
14
+ const raw = process.env[name];
15
+ if (!raw || raw.trim().length === 0) return fallback;
16
+ const normalized = raw.trim().toLowerCase();
17
+ if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
18
+ if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
19
+ throw new Error(`${name} must be a boolean (true/false), got: ${raw}`);
20
+ }
21
+
22
+ function readPackageVersion(): string | undefined {
23
+ try {
24
+ const packageJsonUrl = new URL('../package.json', import.meta.url);
25
+ const parsed = JSON.parse(fs.readFileSync(packageJsonUrl, 'utf8')) as { version?: unknown };
26
+ return typeof parsed.version === 'string' && parsed.version.trim().length > 0
27
+ ? parsed.version.trim()
28
+ : undefined;
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ async function main() {
35
+ const host = process.env.HOST ?? '0.0.0.0';
36
+ const port = Number(process.env.PORT ?? '8788');
37
+ const resolveDocPath = process.env.TREECRDT_DISCOVERY_RESOLVE_PATH?.trim() || undefined;
38
+ const publicHttpBaseUrl =
39
+ process.env.TREECRDT_DISCOVERY_PUBLIC_HTTP_BASE_URL?.trim() || undefined;
40
+ const publicWebSocketBaseUrl =
41
+ process.env.TREECRDT_DISCOVERY_PUBLIC_WS_BASE_URL?.trim() || undefined;
42
+ const cacheTtlMs = Number(process.env.TREECRDT_DISCOVERY_CACHE_TTL_MS ?? String(60 * 60 * 1000));
43
+ const packageVersion = readPackageVersion();
44
+ const gitSha = process.env.TREECRDT_DISCOVERY_GIT_SHA?.trim() || undefined;
45
+ const gitDirty = parseBooleanEnv('TREECRDT_DISCOVERY_GIT_DIRTY', false);
46
+ const startedAt = new Date().toISOString();
47
+
48
+ if (!Number.isFinite(port) || port <= 0) throw new Error(`invalid PORT: ${process.env.PORT}`);
49
+ if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
50
+ throw new Error('invalid TREECRDT_DISCOVERY_CACHE_TTL_MS');
51
+ }
52
+
53
+ const handle = await startDiscoveryServer({
54
+ host,
55
+ port,
56
+ resolveDocPath,
57
+ publicHttpBaseUrl,
58
+ publicWebSocketBaseUrl,
59
+ cacheTtlMs,
60
+ packageVersion,
61
+ gitSha,
62
+ gitDirty,
63
+ startedAt,
64
+ });
65
+ const clientHost = clientHostForBindHost(handle.host);
66
+ console.log(`TreeCRDT discovery server listening on ${handle.host}:${handle.port}`);
67
+ console.log(`- bind: http://${handle.host}:${handle.port}`);
68
+ console.log(`- health: http://${clientHost}:${handle.port}/health`);
69
+ console.log(`- status: http://${clientHost}:${handle.port}/status`);
70
+ console.log(
71
+ `- resolve: http://${clientHost}:${handle.port}${resolveDocPath ?? '/resolve-doc'}?docId=YOUR_DOC_ID`,
72
+ );
73
+ if (publicHttpBaseUrl || publicWebSocketBaseUrl) {
74
+ console.log(
75
+ `- advertised endpoints: ${publicHttpBaseUrl ?? '(derived from request)'} / ${
76
+ publicWebSocketBaseUrl ?? '(derived from request)'
77
+ }`,
78
+ );
79
+ }
80
+ }
81
+
82
+ main().catch((err) => {
83
+ console.error(err);
84
+ process.exitCode = 1;
85
+ });
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './server.js';
package/src/server.ts ADDED
@@ -0,0 +1,310 @@
1
+ import http from 'node:http';
2
+
3
+ import type { ResolveDocRequest, ResolveDocResponse } from '@treecrdt/discovery';
4
+
5
+ type Awaitable<T> = T | Promise<T>;
6
+
7
+ export type DiscoveryServerResolveContext = {
8
+ req: http.IncomingMessage;
9
+ url: URL;
10
+ };
11
+
12
+ export type DiscoveryServerResolveHandler = (
13
+ request: ResolveDocRequest,
14
+ ctx: DiscoveryServerResolveContext,
15
+ ) => Awaitable<ResolveDocResponse>;
16
+
17
+ export type DiscoveryServerHealthResult =
18
+ | {
19
+ ok: true;
20
+ body?: string;
21
+ contentType?: string;
22
+ }
23
+ | {
24
+ ok: false;
25
+ statusCode?: number;
26
+ body?: string;
27
+ contentType?: string;
28
+ };
29
+
30
+ export type DiscoveryServerOptions = {
31
+ host?: string;
32
+ port?: number;
33
+ healthPath?: string;
34
+ statusPath?: string;
35
+ resolveDocPath?: string;
36
+ publicHttpBaseUrl?: string;
37
+ publicWebSocketBaseUrl?: string;
38
+ cacheTtlMs?: number;
39
+ resolveDoc?: DiscoveryServerResolveHandler;
40
+ healthCheck?: () => Awaitable<DiscoveryServerHealthResult>;
41
+ statusInfo?: () => Awaitable<Record<string, unknown>>;
42
+ packageName?: string;
43
+ packageVersion?: string;
44
+ gitSha?: string;
45
+ gitDirty?: boolean;
46
+ startedAt?: string;
47
+ };
48
+
49
+ export type DiscoveryServerHandle = {
50
+ host: string;
51
+ port: number;
52
+ close: () => Promise<void>;
53
+ };
54
+
55
+ function normalizeOptionalAbsoluteUrl(
56
+ name: string,
57
+ value: string | undefined,
58
+ allowedProtocols: readonly string[],
59
+ ): string | undefined {
60
+ if (!value) return undefined;
61
+ const trimmed = value.trim();
62
+ if (trimmed.length === 0) return undefined;
63
+ let url: URL;
64
+ try {
65
+ url = new URL(trimmed);
66
+ } catch {
67
+ throw new Error(`${name} must be a valid absolute URL`);
68
+ }
69
+ if (!allowedProtocols.includes(url.protocol)) {
70
+ throw new Error(`${name} must use ${allowedProtocols.join(', ')}`);
71
+ }
72
+ return url.toString().replace(/\/$/, '');
73
+ }
74
+
75
+ function normalizePath(name: string, value: string | undefined, fallback: string): string {
76
+ const trimmed = value?.trim() || fallback;
77
+ if (!trimmed.startsWith('/')) throw new Error(`${name} must start with "/"`);
78
+ return trimmed;
79
+ }
80
+
81
+ function firstForwardedHeader(value: string | string[] | undefined): string | undefined {
82
+ if (Array.isArray(value)) value = value[0];
83
+ if (!value) return undefined;
84
+ const first = value.split(',')[0]?.trim();
85
+ return first && first.length > 0 ? first : undefined;
86
+ }
87
+
88
+ function derivePublicBaseUrl(req: http.IncomingMessage, fallbackProtocol: 'http' | 'ws'): string {
89
+ const host =
90
+ firstForwardedHeader(req.headers['x-forwarded-host']) ?? req.headers.host ?? 'localhost';
91
+ const forwardedProto = firstForwardedHeader(req.headers['x-forwarded-proto']);
92
+ const protocol =
93
+ forwardedProto && forwardedProto.length > 0
94
+ ? fallbackProtocol === 'ws'
95
+ ? forwardedProto === 'https'
96
+ ? 'wss'
97
+ : 'ws'
98
+ : forwardedProto
99
+ : fallbackProtocol;
100
+ return `${protocol}://${host}`.replace(/\/$/, '');
101
+ }
102
+
103
+ function buildDefaultResolveDocHandler(opts: {
104
+ publicHttpBaseUrl?: string;
105
+ publicWebSocketBaseUrl?: string;
106
+ cacheTtlMs: number;
107
+ }): DiscoveryServerResolveHandler {
108
+ return async (request, ctx) => {
109
+ const publicHttpBaseUrl = opts.publicHttpBaseUrl ?? derivePublicBaseUrl(ctx.req, 'http');
110
+ const publicWebSocketBaseUrl =
111
+ opts.publicWebSocketBaseUrl ?? derivePublicBaseUrl(ctx.req, 'ws');
112
+ return {
113
+ docId: request.docId,
114
+ plan: {
115
+ topology: 'relay',
116
+ attachments: [
117
+ {
118
+ protocol: 'websocket',
119
+ role: 'preferred',
120
+ url: `${publicWebSocketBaseUrl}/sync`,
121
+ },
122
+ {
123
+ protocol: 'https',
124
+ role: 'bootstrap',
125
+ url: publicHttpBaseUrl,
126
+ },
127
+ ],
128
+ cacheTtlMs: opts.cacheTtlMs,
129
+ },
130
+ };
131
+ };
132
+ }
133
+
134
+ export async function startDiscoveryServer(
135
+ opts: DiscoveryServerOptions = {},
136
+ ): Promise<DiscoveryServerHandle> {
137
+ const host = opts.host ?? '0.0.0.0';
138
+ const port = Number(opts.port ?? 8788);
139
+ const healthPath = normalizePath('healthPath', opts.healthPath, '/health');
140
+ const statusPath = normalizePath('statusPath', opts.statusPath, '/status');
141
+ const resolveDocPath = normalizePath('resolveDocPath', opts.resolveDocPath, '/resolve-doc');
142
+ const publicHttpBaseUrl = normalizeOptionalAbsoluteUrl(
143
+ 'publicHttpBaseUrl',
144
+ opts.publicHttpBaseUrl,
145
+ ['http:', 'https:'],
146
+ );
147
+ const publicWebSocketBaseUrl = normalizeOptionalAbsoluteUrl(
148
+ 'publicWebSocketBaseUrl',
149
+ opts.publicWebSocketBaseUrl,
150
+ ['ws:', 'wss:', 'http:', 'https:'],
151
+ );
152
+ const cacheTtlMs = opts.cacheTtlMs == null ? 60 * 60 * 1000 : Number(opts.cacheTtlMs);
153
+ const packageName = opts.packageName?.trim() || '@treecrdt/discovery-server-node';
154
+ const packageVersion = opts.packageVersion?.trim() || undefined;
155
+ const gitSha = opts.gitSha?.trim() || undefined;
156
+ const gitDirty = Boolean(opts.gitDirty);
157
+ const startedAt = opts.startedAt?.trim() || new Date().toISOString();
158
+ const startedAtMs = Date.parse(startedAt);
159
+
160
+ if (!Number.isFinite(port) || port < 0) throw new Error(`invalid port: ${opts.port}`);
161
+ if (!Number.isFinite(cacheTtlMs) || cacheTtlMs < 0) {
162
+ throw new Error(`invalid cacheTtlMs: ${opts.cacheTtlMs}`);
163
+ }
164
+
165
+ const resolveDoc =
166
+ opts.resolveDoc ??
167
+ buildDefaultResolveDocHandler({
168
+ publicHttpBaseUrl,
169
+ publicWebSocketBaseUrl,
170
+ cacheTtlMs,
171
+ });
172
+ const discoveryCorsHeaders = {
173
+ 'access-control-allow-origin': '*',
174
+ 'access-control-allow-methods': 'GET,OPTIONS',
175
+ 'access-control-allow-headers': 'content-type,authorization',
176
+ };
177
+
178
+ const server = http.createServer((req, res) => {
179
+ const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
180
+
181
+ if (url.pathname === healthPath) {
182
+ void (async () => {
183
+ try {
184
+ const result = (await opts.healthCheck?.()) ?? { ok: true as const };
185
+ if (result.ok) {
186
+ res.writeHead(200, { 'content-type': result.contentType ?? 'text/plain' });
187
+ res.end(result.body ?? 'ok');
188
+ return;
189
+ }
190
+ const requestedStatusCode = result.statusCode;
191
+ const statusCode =
192
+ typeof requestedStatusCode === 'number' &&
193
+ Number.isInteger(requestedStatusCode) &&
194
+ requestedStatusCode >= 400 &&
195
+ requestedStatusCode <= 599
196
+ ? requestedStatusCode
197
+ : 503;
198
+ res.writeHead(statusCode, { 'content-type': result.contentType ?? 'text/plain' });
199
+ res.end(result.body ?? 'not ready');
200
+ } catch {
201
+ res.writeHead(503, { 'content-type': 'text/plain' });
202
+ res.end('not ready');
203
+ }
204
+ })();
205
+ return;
206
+ }
207
+
208
+ if (url.pathname === statusPath) {
209
+ void (async () => {
210
+ try {
211
+ const status = {
212
+ ok: true,
213
+ service: packageName,
214
+ version: packageVersion ?? null,
215
+ gitSha: gitSha ?? null,
216
+ gitDirty,
217
+ buildRef: gitSha ? `${gitSha}${gitDirty ? '-dirty' : ''}` : null,
218
+ startedAt,
219
+ uptimeMs: Number.isFinite(startedAtMs) ? Math.max(0, Date.now() - startedAtMs) : null,
220
+ resolveDocPath,
221
+ publicHttpBaseUrl: publicHttpBaseUrl ?? null,
222
+ publicWebSocketBaseUrl: publicWebSocketBaseUrl ?? null,
223
+ cacheTtlMs,
224
+ ...((await opts.statusInfo?.()) ?? {}),
225
+ };
226
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
227
+ res.end(JSON.stringify(status));
228
+ } catch {
229
+ res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
230
+ res.end(JSON.stringify({ ok: false, error: 'status unavailable' }));
231
+ }
232
+ })();
233
+ return;
234
+ }
235
+
236
+ if (url.pathname === resolveDocPath) {
237
+ void (async () => {
238
+ try {
239
+ if (req.method === 'OPTIONS') {
240
+ res.writeHead(204, discoveryCorsHeaders);
241
+ res.end();
242
+ return;
243
+ }
244
+ if (req.method && req.method !== 'GET') {
245
+ res.writeHead(405, {
246
+ 'content-type': 'application/json; charset=utf-8',
247
+ ...discoveryCorsHeaders,
248
+ });
249
+ res.end(JSON.stringify({ ok: false, error: 'method not allowed' }));
250
+ return;
251
+ }
252
+ const docId = url.searchParams.get('docId')?.trim();
253
+ if (!docId) {
254
+ res.writeHead(400, {
255
+ 'content-type': 'application/json; charset=utf-8',
256
+ ...discoveryCorsHeaders,
257
+ });
258
+ res.end(JSON.stringify({ ok: false, error: 'missing docId' }));
259
+ return;
260
+ }
261
+ const response = await resolveDoc({ docId }, { req, url });
262
+ res.writeHead(200, {
263
+ 'content-type': 'application/json; charset=utf-8',
264
+ ...discoveryCorsHeaders,
265
+ });
266
+ res.end(JSON.stringify(response));
267
+ } catch {
268
+ res.writeHead(500, {
269
+ 'content-type': 'application/json; charset=utf-8',
270
+ ...discoveryCorsHeaders,
271
+ });
272
+ res.end(JSON.stringify({ ok: false, error: 'resolve failed' }));
273
+ }
274
+ })();
275
+ return;
276
+ }
277
+
278
+ res.writeHead(404, { 'content-type': 'text/plain' });
279
+ res.end('not found');
280
+ });
281
+
282
+ await new Promise<void>((resolve, reject) => {
283
+ const onError = (error: Error) => {
284
+ server.off('listening', onListening);
285
+ reject(error);
286
+ };
287
+ const onListening = () => {
288
+ server.off('error', onError);
289
+ resolve();
290
+ };
291
+ server.once('error', onError);
292
+ server.once('listening', onListening);
293
+ server.listen(port, host);
294
+ });
295
+
296
+ const address = server.address();
297
+ if (!address || typeof address === 'string') {
298
+ throw new Error('failed to start discovery server');
299
+ }
300
+
301
+ return {
302
+ host: address.address,
303
+ port: address.port,
304
+ close: async () => {
305
+ await new Promise<void>((resolve, reject) => {
306
+ server.close((err) => (err ? reject(err) : resolve()));
307
+ });
308
+ },
309
+ };
310
+ }