@volter/world-runtime 2.0.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 +202 -0
- package/dist/known-external-services.json +1108 -0
- package/dist/src/ancestry.d.ts +2 -0
- package/dist/src/ancestry.js +42 -0
- package/dist/src/app-url.d.ts +47 -0
- package/dist/src/app-url.js +239 -0
- package/dist/src/attach.d.ts +48 -0
- package/dist/src/attach.js +87 -0
- package/dist/src/branch.d.ts +20 -0
- package/dist/src/branch.js +65 -0
- package/dist/src/browser-proxy-cli.d.ts +2 -0
- package/dist/src/browser-proxy-cli.js +41 -0
- package/dist/src/ca-trust.d.ts +5 -0
- package/dist/src/ca-trust.js +64 -0
- package/dist/src/catalog.d.ts +31 -0
- package/dist/src/catalog.js +148 -0
- package/dist/src/changeset.d.ts +142 -0
- package/dist/src/changeset.js +570 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +1262 -0
- package/dist/src/command-lifetime.d.ts +15 -0
- package/dist/src/command-lifetime.js +98 -0
- package/dist/src/configs.d.ts +18 -0
- package/dist/src/configs.js +119 -0
- package/dist/src/console-apart.d.ts +38 -0
- package/dist/src/console-apart.js +107 -0
- package/dist/src/consumers.d.ts +46 -0
- package/dist/src/consumers.js +200 -0
- package/dist/src/covers.d.ts +183 -0
- package/dist/src/covers.js +800 -0
- package/dist/src/fixture-env.d.ts +42 -0
- package/dist/src/fixture-env.js +221 -0
- package/dist/src/host-cli.d.ts +2 -0
- package/dist/src/host-cli.js +92 -0
- package/dist/src/host-fault-fixture.d.ts +32 -0
- package/dist/src/host-fault-fixture.js +100 -0
- package/dist/src/host-worker.d.ts +1 -0
- package/dist/src/host-worker.js +23 -0
- package/dist/src/host.d.ts +38 -0
- package/dist/src/host.js +135 -0
- package/dist/src/index.d.ts +48 -0
- package/dist/src/index.js +35 -0
- package/dist/src/infra-cli.d.ts +2 -0
- package/dist/src/infra-cli.js +136 -0
- package/dist/src/init.d.ts +227 -0
- package/dist/src/init.js +1117 -0
- package/dist/src/inject-map.d.ts +34 -0
- package/dist/src/inject-map.js +56 -0
- package/dist/src/lifecycle-record.d.ts +47 -0
- package/dist/src/lifecycle-record.js +196 -0
- package/dist/src/origin.d.ts +31 -0
- package/dist/src/origin.js +139 -0
- package/dist/src/pack-facts.d.ts +75 -0
- package/dist/src/pack-facts.js +98 -0
- package/dist/src/pglite-backing.d.ts +21 -0
- package/dist/src/pglite-backing.js +158 -0
- package/dist/src/pglite-host.mjs +147 -0
- package/dist/src/placeholder.d.ts +20 -0
- package/dist/src/placeholder.js +100 -0
- package/dist/src/prerequisites.d.ts +21 -0
- package/dist/src/prerequisites.js +49 -0
- package/dist/src/process-groups.d.ts +4 -0
- package/dist/src/process-groups.js +49 -0
- package/dist/src/project-inspect.d.ts +109 -0
- package/dist/src/project-inspect.js +827 -0
- package/dist/src/proxy-daemon.d.ts +2 -0
- package/dist/src/proxy-daemon.js +18 -0
- package/dist/src/redirect-proxy.d.ts +105 -0
- package/dist/src/redirect-proxy.js +665 -0
- package/dist/src/reflect.d.ts +74 -0
- package/dist/src/reflect.js +392 -0
- package/dist/src/resources.d.ts +26 -0
- package/dist/src/resources.js +22 -0
- package/dist/src/root.d.ts +114 -0
- package/dist/src/root.js +312 -0
- package/dist/src/run-task-worker.d.ts +1 -0
- package/dist/src/run-task-worker.js +38 -0
- package/dist/src/run-task.d.ts +18 -0
- package/dist/src/run-task.js +48 -0
- package/dist/src/runtime-test-support.d.ts +59 -0
- package/dist/src/runtime-test-support.js +205 -0
- package/dist/src/runtime.d.ts +256 -0
- package/dist/src/runtime.js +3502 -0
- package/dist/src/schema.d.ts +449 -0
- package/dist/src/schema.js +605 -0
- package/dist/src/serve.d.ts +30 -0
- package/dist/src/serve.js +82 -0
- package/dist/src/served-world.d.ts +194 -0
- package/dist/src/served-world.js +986 -0
- package/dist/src/service-exit.d.ts +46 -0
- package/dist/src/service-exit.js +195 -0
- package/dist/src/service-recorder.d.ts +1 -0
- package/dist/src/service-recorder.js +121 -0
- package/dist/src/sibling.d.ts +1 -0
- package/dist/src/sibling.js +9 -0
- package/dist/src/signals.d.ts +1 -0
- package/dist/src/signals.js +11 -0
- package/dist/src/storage-capacity.d.ts +8 -0
- package/dist/src/storage-capacity.js +61 -0
- package/dist/src/tail.d.ts +30 -0
- package/dist/src/tail.js +160 -0
- package/dist/src/tcp-port.d.ts +2 -0
- package/dist/src/tcp-port.js +36 -0
- package/dist/src/up-task-worker.d.ts +1 -0
- package/dist/src/up-task-worker.js +61 -0
- package/dist/src/up-task.d.ts +17 -0
- package/dist/src/up-task.js +49 -0
- package/dist/src/websocket-relay.d.ts +3 -0
- package/dist/src/websocket-relay.js +40 -0
- package/known-external-services.json +1108 -0
- package/package.json +83 -0
- package/src/ancestry.ts +36 -0
- package/src/app-url.ts +253 -0
- package/src/attach.ts +117 -0
- package/src/branch.ts +63 -0
- package/src/browser-proxy-cli.ts +44 -0
- package/src/ca-trust.ts +57 -0
- package/src/catalog.ts +156 -0
- package/src/changeset.ts +627 -0
- package/src/cli.ts +1111 -0
- package/src/command-lifetime.ts +79 -0
- package/src/configs.ts +110 -0
- package/src/console-apart.ts +90 -0
- package/src/consumers.ts +185 -0
- package/src/covers.ts +934 -0
- package/src/fixture-env.ts +230 -0
- package/src/host-cli.ts +90 -0
- package/src/host-worker.ts +23 -0
- package/src/host.ts +169 -0
- package/src/index.ts +171 -0
- package/src/infra-cli.ts +133 -0
- package/src/init.ts +1316 -0
- package/src/inject-map.ts +72 -0
- package/src/lifecycle-record.ts +168 -0
- package/src/origin.ts +134 -0
- package/src/pack-facts.ts +128 -0
- package/src/pglite-backing.ts +141 -0
- package/src/pglite-host.mjs +147 -0
- package/src/placeholder.ts +89 -0
- package/src/prerequisites.ts +66 -0
- package/src/process-groups.ts +33 -0
- package/src/project-inspect.ts +770 -0
- package/src/proxy-daemon.ts +21 -0
- package/src/redirect-proxy.ts +684 -0
- package/src/reflect.ts +440 -0
- package/src/resources.ts +22 -0
- package/src/root.ts +290 -0
- package/src/run-task-worker.ts +27 -0
- package/src/run-task.ts +44 -0
- package/src/runtime-test-support.ts +208 -0
- package/src/runtime.ts +3357 -0
- package/src/schema.ts +922 -0
- package/src/serve.ts +102 -0
- package/src/served-world.ts +812 -0
- package/src/service-exit.ts +175 -0
- package/src/service-recorder.ts +89 -0
- package/src/sibling.ts +10 -0
- package/src/signals.ts +10 -0
- package/src/storage-capacity.ts +60 -0
- package/src/tail.ts +205 -0
- package/src/tcp-port.ts +35 -0
- package/src/up-task-worker.ts +40 -0
- package/src/up-task.ts +45 -0
- package/src/websocket-relay.ts +32 -0
package/src/reflect.ts
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
import { serveHttp, type HttpServer } from '@volter/world-core';
|
|
2
|
+
import { websocketRelay } from './websocket-relay.ts';
|
|
3
|
+
import { sessionTrustEnv } from './ca-trust.ts';
|
|
4
|
+
// The reflect attachment (docs/guides/route-a-cli-through-the-world.md): attach an UNMODIFIED consumer —
|
|
5
|
+
// any language, any binary, no proxy env, no injector — by answering routed
|
|
6
|
+
// vendor hosts' DNS with the world's own TLS front. The consumer's ordinary
|
|
7
|
+
// `https://api.stripe.com` call roundtrips into the front, which terminates
|
|
8
|
+
// TLS with the session CA's per-host leaf (exactly the redirect-proxy's
|
|
9
|
+
// machinery) and forwards to the twin. Hosts that are not routed resolve real
|
|
10
|
+
// and never touch the world: passthrough is the default.
|
|
11
|
+
//
|
|
12
|
+
// Two small servers, both world-side ("the door belongs to the world"):
|
|
13
|
+
// • the FRONT — a TCP listener that peeks the TLS ClientHello SNI and pipes
|
|
14
|
+
// the raw bytes to a per-host leaf-cert https server (the same
|
|
15
|
+
// one-server-per-host trick redirect-proxy uses for CONNECT, reused here
|
|
16
|
+
// because Bun does not honor SNICallback).
|
|
17
|
+
// • the RESOLVER — a UDP DNS server ("the ear", pointed at by the attacher's
|
|
18
|
+
// environment, e.g. `docker run --dns`): A-answers routed hosts with the
|
|
19
|
+
// front's address (TTL 0 — a route flip lands on the next lookup),
|
|
20
|
+
// empty-answers AAAA for routed hosts (else real IPv6 wins), and forwards
|
|
21
|
+
// everything else to the real upstream untouched.
|
|
22
|
+
//
|
|
23
|
+
// ROUTES are attachment-scoped state (docs/guides/route-a-cli-through-the-world.md): one host per line in
|
|
24
|
+
// the instance's reflect-routes file, re-read live. The world stays ignorant
|
|
25
|
+
// of who is attached; routes only select interception. v1 routes are exact
|
|
26
|
+
// lowercase hostnames (wildcard families like *.atlassian.net: route the
|
|
27
|
+
// specific hosts the consumer uses).
|
|
28
|
+
//
|
|
29
|
+
// Per CLAUDE.md the runtime stays a lifecycle primitive: `reflect` runs in the
|
|
30
|
+
// foreground and supervises nothing; composition (containers, --dns wiring)
|
|
31
|
+
// lives in the cookbook recipe.
|
|
32
|
+
import dgram from 'node:dgram';
|
|
33
|
+
import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
34
|
+
import { connect as netConnect, createServer as createNetServer, type Server as NetServer, type Socket } from 'node:net';
|
|
35
|
+
import { join } from 'node:path';
|
|
36
|
+
import { activeVendorMap, ensureCa, leafCertFor, noTwinMessage, proxyTargetFor, twinUnreachableMessage } from './redirect-proxy.ts';
|
|
37
|
+
import { instanceDir } from './runtime.ts';
|
|
38
|
+
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Routes — attachment-scoped, file-backed, re-read live by the resolver.
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
export function reflectRoutesPath(root: string, name: string): string {
|
|
44
|
+
return join(instanceDir(root, name), 'reflect-routes');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readReflectRoutes(path: string): Set<string> {
|
|
48
|
+
if (!existsSync(path)) return new Set();
|
|
49
|
+
return new Set(
|
|
50
|
+
readFileSync(path, 'utf8')
|
|
51
|
+
.split('\n')
|
|
52
|
+
.map((line) => line.trim().toLowerCase())
|
|
53
|
+
.filter((line) => line.length > 0 && !line.startsWith('#')),
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function writeReflectRoutes(path: string, routes: Set<string>): void {
|
|
58
|
+
writeFileSync(path, `${[...routes].sort().join('\n')}\n`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// SNI peek — minimal ClientHello parser (records buffered until complete).
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
/** Extract the SNI server name from a buffered TLS ClientHello, `undefined` if
|
|
66
|
+
* the buffer is not yet a complete handshake record or carries no SNI. */
|
|
67
|
+
export function parseSni(buffer: Buffer): string | undefined {
|
|
68
|
+
if (buffer.length < 5 || buffer[0] !== 0x16) return undefined; // not a TLS handshake record
|
|
69
|
+
const recordLength = buffer.readUInt16BE(3);
|
|
70
|
+
if (buffer.length < 5 + recordLength) return undefined; // incomplete — keep buffering
|
|
71
|
+
let offset = 5;
|
|
72
|
+
if (buffer[offset] !== 0x01) return undefined; // not a ClientHello
|
|
73
|
+
offset += 4; // handshake type + 24-bit length
|
|
74
|
+
offset += 2 + 32; // client version + random
|
|
75
|
+
const sessionIdLength = buffer[offset]!;
|
|
76
|
+
offset += 1 + sessionIdLength;
|
|
77
|
+
const cipherLength = buffer.readUInt16BE(offset);
|
|
78
|
+
offset += 2 + cipherLength;
|
|
79
|
+
const compressionLength = buffer[offset]!;
|
|
80
|
+
offset += 1 + compressionLength;
|
|
81
|
+
if (offset + 2 > buffer.length) return undefined;
|
|
82
|
+
const extensionsEnd = offset + 2 + buffer.readUInt16BE(offset);
|
|
83
|
+
offset += 2;
|
|
84
|
+
while (offset + 4 <= extensionsEnd && offset + 4 <= buffer.length) {
|
|
85
|
+
const extensionType = buffer.readUInt16BE(offset);
|
|
86
|
+
const extensionLength = buffer.readUInt16BE(offset + 2);
|
|
87
|
+
offset += 4;
|
|
88
|
+
if (extensionType === 0x0000) {
|
|
89
|
+
// server_name: list length (2), entry type (1, 0 = hostname), name length (2), name
|
|
90
|
+
const nameLength = buffer.readUInt16BE(offset + 3);
|
|
91
|
+
return buffer.subarray(offset + 5, offset + 5 + nameLength).toString('ascii').toLowerCase();
|
|
92
|
+
}
|
|
93
|
+
offset += extensionLength;
|
|
94
|
+
}
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
// The front.
|
|
100
|
+
// ---------------------------------------------------------------------------
|
|
101
|
+
|
|
102
|
+
export interface ReflectFrontOptions {
|
|
103
|
+
/** live env source — the world's twin map, exactly like the redirect proxy */
|
|
104
|
+
envLoader: () => Record<string, string | undefined>;
|
|
105
|
+
tlsDir: string;
|
|
106
|
+
host?: string;
|
|
107
|
+
port?: number;
|
|
108
|
+
/** additional SNI names to terminate (a served world's ADVERTISED hostname):
|
|
109
|
+
* the per-host handler already routes by Host header, so env-attached
|
|
110
|
+
* traffic arriving with SNI=<advertised> and Host=<vendor> lands in the
|
|
111
|
+
* right twin through the one door (docs/guides/route-a-cli-through-the-world.md, remote worlds). */
|
|
112
|
+
extraHosts?: string[];
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface ReflectFrontHandle {
|
|
116
|
+
host: string;
|
|
117
|
+
port: number;
|
|
118
|
+
caCertPath: string;
|
|
119
|
+
close(): Promise<void>;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function startReflectFront(options: ReflectFrontOptions): Promise<ReflectFrontHandle> {
|
|
123
|
+
const host = options.host ?? '0.0.0.0';
|
|
124
|
+
const ca = ensureCa(options.tlsDir);
|
|
125
|
+
const openSockets = new Set<Socket>();
|
|
126
|
+
const hostServers = new Map<string, HttpServer>();
|
|
127
|
+
const hostPorts = new Map<string, number>();
|
|
128
|
+
|
|
129
|
+
// One TLS server per vendor host (the leaf cert names it), behind the SNI door. Bun's own server: it
|
|
130
|
+
// terminates TLS, forwards each request to the twin, and relays a websocket upgrade (a bot's gateway,
|
|
131
|
+
// a streaming API) to the twin's websocket — under Bun, node:http's 'upgrade' socket cannot write back
|
|
132
|
+
// to the client, so the relay is message-level, both ways.
|
|
133
|
+
const ensureHostServer = async (vendorHost: string): Promise<number> => {
|
|
134
|
+
const existing = hostPorts.get(vendorHost);
|
|
135
|
+
if (existing) return existing;
|
|
136
|
+
const leaf = leafCertFor(vendorHost, ca);
|
|
137
|
+
const resolveTwin = (req: Request): { origin: string; path: string; vendor: string } | { refuse: Response } => {
|
|
138
|
+
const url = new URL(req.url);
|
|
139
|
+
const hostHeader = (req.headers.get('host') ?? vendorHost).split(':')[0] ?? vendorHost;
|
|
140
|
+
const env = options.envLoader();
|
|
141
|
+
const prefixMatch = url.pathname.match(/^\/__vendor\/([a-z0-9-]+)(\/.*)?$/);
|
|
142
|
+
if (prefixMatch) {
|
|
143
|
+
const origin = activeVendorMap(env)[prefixMatch[1]!];
|
|
144
|
+
if (origin === undefined) return { refuse: new Response('no twin for vendor', { status: 502 }) };
|
|
145
|
+
return { origin, path: `${prefixMatch[2] ?? '/'}${url.search}`, vendor: prefixMatch[1]! };
|
|
146
|
+
}
|
|
147
|
+
const twin = proxyTargetFor(hostHeader, env, url.pathname) ?? proxyTargetFor(vendorHost, env, url.pathname);
|
|
148
|
+
if (!twin) return { refuse: new Response(noTwinMessage(hostHeader, url.pathname), { status: 502, headers: { 'content-type': 'text/plain; charset=utf-8' } }) };
|
|
149
|
+
return { origin: twin.origin, path: `${url.pathname}${url.search}`, vendor: twin.vendor };
|
|
150
|
+
};
|
|
151
|
+
const hostServer = await serveHttp({
|
|
152
|
+
hostname: '127.0.0.1',
|
|
153
|
+
port: 0,
|
|
154
|
+
tls: { key: leaf.key, cert: leaf.cert },
|
|
155
|
+
idleTimeout: 255,
|
|
156
|
+
async fetch(req) {
|
|
157
|
+
const target = resolveTwin(req);
|
|
158
|
+
if ('refuse' in target) return target.refuse;
|
|
159
|
+
let origin: URL;
|
|
160
|
+
try { origin = new URL(target.origin); } catch { return new Response('bad twin origin', { status: 502 }); }
|
|
161
|
+
|
|
162
|
+
const headers = new Headers(req.headers);
|
|
163
|
+
headers.delete('proxy-connection');
|
|
164
|
+
headers.delete('accept-encoding');
|
|
165
|
+
// the consumer spoke TLS to the front; a twin that answers with an absolute URL (Slack's Socket Mode link)
|
|
166
|
+
// gives the scheme the consumer can reach again, as a vendor behind a TLS-terminating edge does
|
|
167
|
+
headers.set('x-forwarded-proto', 'https');
|
|
168
|
+
try {
|
|
169
|
+
const upstream = await fetch(`${origin.origin}${target.path}`, { method: req.method, headers, body: req.body, ...(req.body ? { duplex: 'half' as const } : {}), redirect: 'manual' });
|
|
170
|
+
const out = new Headers(upstream.headers);
|
|
171
|
+
out.delete('content-encoding');
|
|
172
|
+
out.delete('content-length');
|
|
173
|
+
out.delete('transfer-encoding');
|
|
174
|
+
out.delete('connection');
|
|
175
|
+
out.delete('keep-alive');
|
|
176
|
+
return new Response(upstream.body, { status: upstream.status, headers: out });
|
|
177
|
+
} catch (error) {
|
|
178
|
+
let world: string | undefined;
|
|
179
|
+
try { world = options.envLoader().VOLTER_WORLD; } catch { /* the answer still goes out */ }
|
|
180
|
+
return new Response(twinUnreachableMessage(target.vendor, origin.origin, error instanceof Error ? error : new Error(String(error)), world), { status: 502 });
|
|
181
|
+
}
|
|
182
|
+
},
|
|
183
|
+
upgrade: websocketRelay(req => {
|
|
184
|
+
const target = resolveTwin(req);
|
|
185
|
+
if ('refuse' in target) return undefined;
|
|
186
|
+
const origin = new URL(target.origin);
|
|
187
|
+
return `${origin.protocol === 'https:' ? 'wss' : 'ws'}://${origin.host}${target.path}`;
|
|
188
|
+
}),
|
|
189
|
+
});
|
|
190
|
+
const hostPort = Number(hostServer.port);
|
|
191
|
+
hostServers.set(vendorHost, hostServer);
|
|
192
|
+
hostPorts.set(vendorHost, hostPort);
|
|
193
|
+
return hostPort;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const server: NetServer = createNetServer((clientSocket: Socket) => {
|
|
197
|
+
openSockets.add(clientSocket);
|
|
198
|
+
clientSocket.on('close', () => openSockets.delete(clientSocket));
|
|
199
|
+
clientSocket.on('error', () => clientSocket.destroy());
|
|
200
|
+
let buffered = Buffer.alloc(0);
|
|
201
|
+
const onData = (chunk: Buffer) => {
|
|
202
|
+
buffered = Buffer.concat([buffered, chunk]);
|
|
203
|
+
const sni = parseSni(buffered);
|
|
204
|
+
if (sni === undefined) {
|
|
205
|
+
if (buffered.length > 65_536) clientSocket.destroy(); // not a ClientHello — give up
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
clientSocket.removeListener('data', onData);
|
|
209
|
+
const twin = proxyTargetFor(sni, options.envLoader());
|
|
210
|
+
if (!twin && !(options.extraHosts ?? []).includes(sni)) {
|
|
211
|
+
// only routed hosts (or the advertised name) are pointed here by the
|
|
212
|
+
// resolver/manifest; anything else is refused, never blind-forwarded
|
|
213
|
+
// (the front is a door to twins, not a general proxy)
|
|
214
|
+
clientSocket.destroy();
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
ensureHostServer(sni)
|
|
218
|
+
.then((port) => {
|
|
219
|
+
const upstream: Socket = netConnect(port, '127.0.0.1');
|
|
220
|
+
openSockets.add(upstream);
|
|
221
|
+
upstream.on('close', () => openSockets.delete(upstream));
|
|
222
|
+
upstream.on('error', () => clientSocket.destroy());
|
|
223
|
+
clientSocket.on('error', () => upstream.destroy());
|
|
224
|
+
upstream.write(buffered);
|
|
225
|
+
upstream.pipe(clientSocket);
|
|
226
|
+
clientSocket.pipe(upstream);
|
|
227
|
+
})
|
|
228
|
+
.catch(() => clientSocket.destroy());
|
|
229
|
+
};
|
|
230
|
+
clientSocket.on('data', onData);
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
await new Promise<void>((resolveListen, reject) => {
|
|
234
|
+
server.once('error', reject);
|
|
235
|
+
server.listen(options.port ?? 0, host, () => resolveListen());
|
|
236
|
+
});
|
|
237
|
+
const address = server.address();
|
|
238
|
+
const port = typeof address === 'object' && address ? address.port : (options.port ?? 0);
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
host,
|
|
242
|
+
port,
|
|
243
|
+
caCertPath: ca.caCert,
|
|
244
|
+
async close() {
|
|
245
|
+
for (const socket of openSockets) socket.destroy();
|
|
246
|
+
await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
|
|
247
|
+
for (const hostServer of hostServers.values()) hostServer.stop(true);
|
|
248
|
+
},
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// ---------------------------------------------------------------------------
|
|
253
|
+
// The resolver.
|
|
254
|
+
// ---------------------------------------------------------------------------
|
|
255
|
+
|
|
256
|
+
export interface ReflectResolverOptions {
|
|
257
|
+
/** live route set — re-read per query so a route flip lands immediately */
|
|
258
|
+
routesLoader: () => Set<string>;
|
|
259
|
+
/** the address routed hosts resolve to (the front's reachable IP) */
|
|
260
|
+
targetIp: string;
|
|
261
|
+
upstream?: string;
|
|
262
|
+
/** upstream port — default 53; tests point at a fake upstream on a high port */
|
|
263
|
+
upstreamPort?: number;
|
|
264
|
+
host?: string;
|
|
265
|
+
port?: number;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export interface ReflectResolverHandle {
|
|
269
|
+
port: number;
|
|
270
|
+
close(): Promise<void>;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function dnsQuestion(message: Buffer): { name: string; qtype: number; questionEnd: number } | undefined {
|
|
274
|
+
if (message.length < 17) return undefined;
|
|
275
|
+
const labels: string[] = [];
|
|
276
|
+
let offset = 12;
|
|
277
|
+
while (offset < message.length) {
|
|
278
|
+
const length = message[offset]!;
|
|
279
|
+
if (length === 0) {
|
|
280
|
+
offset += 1;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
labels.push(message.subarray(offset + 1, offset + 1 + length).toString('ascii'));
|
|
284
|
+
offset += 1 + length;
|
|
285
|
+
}
|
|
286
|
+
if (offset + 4 > message.length) return undefined;
|
|
287
|
+
return { name: labels.join('.').toLowerCase(), qtype: message.readUInt16BE(offset), questionEnd: offset + 4 };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function dnsHeader(query: Buffer, answerCount: number): Buffer {
|
|
291
|
+
const header = Buffer.alloc(12);
|
|
292
|
+
query.copy(header, 0, 0, 2); // ID
|
|
293
|
+
header.writeUInt16BE(0x8180, 2); // response, RD|RA, NOERROR
|
|
294
|
+
header.writeUInt16BE(1, 4); // QDCOUNT
|
|
295
|
+
header.writeUInt16BE(answerCount, 6); // ANCOUNT
|
|
296
|
+
return header;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function dnsAnswerA(query: Buffer, questionEnd: number, ip: string): Buffer {
|
|
300
|
+
const answer = Buffer.alloc(16);
|
|
301
|
+
answer.writeUInt16BE(0xc00c, 0); // name: pointer to the question
|
|
302
|
+
answer.writeUInt16BE(1, 2); // TYPE A
|
|
303
|
+
answer.writeUInt16BE(1, 4); // CLASS IN
|
|
304
|
+
answer.writeUInt32BE(0, 6); // TTL 0 — activation flips on the next lookup
|
|
305
|
+
answer.writeUInt16BE(4, 10);
|
|
306
|
+
const parts = ip.split('.').map(Number);
|
|
307
|
+
for (let index = 0; index < 4; index++) answer[12 + index] = parts[index]!;
|
|
308
|
+
return Buffer.concat([dnsHeader(query, 1), query.subarray(12, questionEnd), answer]);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function dnsAnswerEmpty(query: Buffer, questionEnd: number): Buffer {
|
|
312
|
+
return Buffer.concat([dnsHeader(query, 0), query.subarray(12, questionEnd)]);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
export async function startReflectResolver(options: ReflectResolverOptions): Promise<ReflectResolverHandle> {
|
|
316
|
+
const upstream = options.upstream ?? '8.8.8.8';
|
|
317
|
+
const server = dgram.createSocket('udp4');
|
|
318
|
+
server.on('message', (message, rinfo) => {
|
|
319
|
+
const question = dnsQuestion(message);
|
|
320
|
+
if (!question) return;
|
|
321
|
+
if (options.routesLoader().has(question.name)) {
|
|
322
|
+
const reply =
|
|
323
|
+
question.qtype === 1
|
|
324
|
+
? dnsAnswerA(message, question.questionEnd, options.targetIp)
|
|
325
|
+
: dnsAnswerEmpty(message, question.questionEnd); // AAAA etc.: empty, so the reflected A wins
|
|
326
|
+
server.send(reply, rinfo.port, rinfo.address);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
// passthrough: relay to the real upstream untouched
|
|
330
|
+
const forwarder = dgram.createSocket('udp4');
|
|
331
|
+
const timer = setTimeout(() => forwarder.close(), 3_000);
|
|
332
|
+
forwarder.on('message', (response) => {
|
|
333
|
+
clearTimeout(timer);
|
|
334
|
+
server.send(response, rinfo.port, rinfo.address);
|
|
335
|
+
forwarder.close();
|
|
336
|
+
});
|
|
337
|
+
forwarder.send(message, options.upstreamPort ?? 53, upstream);
|
|
338
|
+
});
|
|
339
|
+
await new Promise<void>((resolveListen, reject) => {
|
|
340
|
+
server.once('error', reject);
|
|
341
|
+
server.bind(options.port ?? 0, options.host ?? '0.0.0.0', () => resolveListen());
|
|
342
|
+
});
|
|
343
|
+
return {
|
|
344
|
+
port: server.address().port,
|
|
345
|
+
async close() {
|
|
346
|
+
await new Promise<void>((resolveClose) => server.close(() => resolveClose()));
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---------------------------------------------------------------------------
|
|
352
|
+
// The reflect manifest — what a running `volter-world reflect` listens on, published for attachers
|
|
353
|
+
// (`attach --via reflect`). Written by the verb on start, removed on exit; absent = no front running.
|
|
354
|
+
// ---------------------------------------------------------------------------
|
|
355
|
+
export interface ReflectManifest {
|
|
356
|
+
/** the address routed hosts resolve to — where attachers reach the front (the verb's --target-ip) */
|
|
357
|
+
targetIp: string;
|
|
358
|
+
/** the address attachers reach the resolver at (--resolver-ip; default the target): on some Docker hosts
|
|
359
|
+
* the gateway address answers DNS itself (colima's VM does), so the resolver needs another host address */
|
|
360
|
+
resolverIp: string;
|
|
361
|
+
frontPort: number;
|
|
362
|
+
resolverPort: number;
|
|
363
|
+
caCertPath: string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export function reflectManifestPath(root: string, name: string): string {
|
|
367
|
+
return join(instanceDir(root, name), 'reflect.json');
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
export function writeReflectManifest(root: string, name: string, manifest: ReflectManifest): void {
|
|
371
|
+
writeFileSync(reflectManifestPath(root, name), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
export function readReflectManifest(root: string, name: string): ReflectManifest | undefined {
|
|
375
|
+
const path = reflectManifestPath(root, name);
|
|
376
|
+
if (!existsSync(path)) return undefined;
|
|
377
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<ReflectManifest>;
|
|
378
|
+
if (typeof parsed.targetIp !== 'string' || typeof parsed.frontPort !== 'number' || typeof parsed.resolverPort !== 'number' || typeof parsed.caCertPath !== 'string') return undefined;
|
|
379
|
+
return { ...parsed, resolverIp: typeof parsed.resolverIp === 'string' ? parsed.resolverIp : parsed.targetIp } as ReflectManifest;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
export function clearReflectManifest(root: string, name: string): void {
|
|
383
|
+
const path = reflectManifestPath(root, name);
|
|
384
|
+
if (existsSync(path)) unlinkSync(path);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Where the CA is mounted inside an attached container, and the env that makes its clients trust it. */
|
|
388
|
+
export const ATTACHED_CA_PATH = '/etc/volter-world/ca.pem';
|
|
389
|
+
export const CA_TRUST_ENV = ['SSL_CERT_FILE', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'NODE_EXTRA_CA_CERTS', 'GIT_SSL_CAINFO'] as const;
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* A docker compose override that attaches every named service through reflect: its DNS is the resolver
|
|
393
|
+
* (so routed vendor hosts resolve to the front), `host.docker.internal` stays resolvable (a service-level
|
|
394
|
+
* `dns` bypasses Docker's own resolver, which is what served that name), the session CA is mounted and
|
|
395
|
+
* named by the trust variables the common clients read. Requires the resolver on port 53: Docker takes a
|
|
396
|
+
* DNS address, never a port. Compose merges this after the consumer's own files, touching nothing else.
|
|
397
|
+
*/
|
|
398
|
+
export function composeOverrideForReflect(manifest: ReflectManifest, services: string[], worldName: string): string {
|
|
399
|
+
if (manifest.resolverPort !== 53) throw new Error(`reflect attach: containers take a DNS address, not a port — run the resolver on :53 (it is on :${manifest.resolverPort})`);
|
|
400
|
+
if (manifest.frontPort !== 443) throw new Error(`reflect attach: a consumer reaches https on :443 — run the front on :443 (it is on :${manifest.frontPort})`);
|
|
401
|
+
const trust = sessionTrustEnv(manifest.caCertPath);
|
|
402
|
+
const lines = ['# generated by `volter-world attach --via reflect` — never edit; merged after the consumer\'s own files', 'services:'];
|
|
403
|
+
for (const service of services) {
|
|
404
|
+
lines.push(` ${service}:`);
|
|
405
|
+
lines.push(' dns:', ` - ${manifest.resolverIp}`);
|
|
406
|
+
lines.push(' extra_hosts:', ' - host.docker.internal:host-gateway');
|
|
407
|
+
lines.push(' environment:', ` - VOLTER_WORLD=${worldName}`);
|
|
408
|
+
for (const key of CA_TRUST_ENV) lines.push(` - ${key}=${ATTACHED_CA_PATH}.${key}`);
|
|
409
|
+
lines.push(' volumes:', ...CA_TRUST_ENV.map((key) => ` - ${trust[key]}:${ATTACHED_CA_PATH}.${key}:ro`));
|
|
410
|
+
}
|
|
411
|
+
return `${lines.join('\n')}\n`;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// docker compose's global options that take a value — the override's -f must land after the consumer's own
|
|
415
|
+
// files and before the subcommand, so these are stepped over to find it.
|
|
416
|
+
const COMPOSE_VALUED_OPTIONS = new Set(['-f', '--file', '-p', '--project-name', '--profile', '--env-file', '--project-directory', '--progress', '--parallel', '--ansi']);
|
|
417
|
+
|
|
418
|
+
/** Split `docker [docker flags] compose [compose flags] <subcommand…>`; undefined when it is not a compose command. */
|
|
419
|
+
export function splitDockerComposeArgs(command: string[]): { head: string[]; composeFlags: string[]; tail: string[] } | undefined {
|
|
420
|
+
if (command[0] !== 'docker') return undefined;
|
|
421
|
+
const composeAt = command.indexOf('compose');
|
|
422
|
+
if (composeAt < 0) return undefined;
|
|
423
|
+
const head = command.slice(0, composeAt + 1);
|
|
424
|
+
const composeFlags: string[] = [];
|
|
425
|
+
let i = composeAt + 1;
|
|
426
|
+
while (i < command.length) {
|
|
427
|
+
const arg = command[i]!;
|
|
428
|
+
if (!arg.startsWith('-')) break;
|
|
429
|
+
if (COMPOSE_VALUED_OPTIONS.has(arg)) { composeFlags.push(arg, command[i + 1] ?? ''); i += 2; continue; }
|
|
430
|
+
composeFlags.push(arg); i += 1; // --flag=value or a boolean flag
|
|
431
|
+
}
|
|
432
|
+
return { head, composeFlags, tail: command.slice(i) };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** The same compose command with the override merged last. */
|
|
436
|
+
export function dockerComposeWithOverride(command: string[], overridePath: string): string[] {
|
|
437
|
+
const parts = splitDockerComposeArgs(command);
|
|
438
|
+
if (!parts) return command;
|
|
439
|
+
return [...parts.head, ...parts.composeFlags, '-f', overridePath, ...parts.tail];
|
|
440
|
+
}
|
package/src/resources.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Actual host capacity and lifecycle inventory. Declarations never reduce reported free space.
|
|
2
|
+
import { statfsSync } from 'node:fs';
|
|
3
|
+
import { totalmem } from 'node:os';
|
|
4
|
+
import { resolve } from 'node:path';
|
|
5
|
+
import { inspectWorldLifecycles } from './lifecycle-record.ts';
|
|
6
|
+
import { storagePoolResolver } from './storage-capacity.ts';
|
|
7
|
+
|
|
8
|
+
export function worldResourceReport(root = process.cwd()) {
|
|
9
|
+
const inventory = inspectWorldLifecycles();
|
|
10
|
+
const measuredAt = new Date().toISOString();
|
|
11
|
+
const path = resolve(root);
|
|
12
|
+
let filesystem: { path: string; availableBytes: number | null; totalBytes: number | null; pool: string | null; source: string; error?: string };
|
|
13
|
+
try {
|
|
14
|
+
const fs = statfsSync(path);
|
|
15
|
+
filesystem = { path, availableBytes: Number(fs.bavail) * Number(fs.bsize), totalBytes: Number(fs.blocks) * Number(fs.bsize),
|
|
16
|
+
pool: storagePoolResolver()(path) ?? null, source: 'statfs' };
|
|
17
|
+
} catch (error) {
|
|
18
|
+
filesystem = { path, availableBytes: null, totalBytes: null, pool: null, source: 'statfs', error: (error as NodeJS.ErrnoException).code ?? 'unavailable' };
|
|
19
|
+
}
|
|
20
|
+
return { schemaVersion: 2, accounting: 'observed' as const, measuredAt,
|
|
21
|
+
host: { physicalMemoryBytes: totalmem(), measuredMemoryUsage: false }, filesystem, ...inventory };
|
|
22
|
+
}
|