servlink 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +184 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +311 -0
- package/dist/cli.js.map +1 -0
- package/dist/guard.d.ts +44 -0
- package/dist/guard.js +157 -0
- package/dist/guard.js.map +1 -0
- package/dist/identity.d.ts +20 -0
- package/dist/identity.js +56 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/logs.d.ts +32 -0
- package/dist/logs.js +110 -0
- package/dist/logs.js.map +1 -0
- package/dist/paths.d.ts +14 -0
- package/dist/paths.js +48 -0
- package/dist/paths.js.map +1 -0
- package/dist/protocol.d.ts +130 -0
- package/dist/protocol.js +85 -0
- package/dist/protocol.js.map +1 -0
- package/dist/state.d.ts +34 -0
- package/dist/state.js +50 -0
- package/dist/state.js.map +1 -0
- package/dist/tunnel.d.ts +61 -0
- package/dist/tunnel.js +490 -0
- package/dist/tunnel.js.map +1 -0
- package/dist/wake.d.ts +32 -0
- package/dist/wake.js +136 -0
- package/dist/wake.js.map +1 -0
- package/package.json +52 -4
package/dist/guard.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host-protection guardrails. Everything here is pure and unit-tested.
|
|
3
|
+
*
|
|
4
|
+
* - Target lock: host/port are fixed at startup and must be loopback or a private IP that
|
|
5
|
+
* the operator passed explicitly. Hostnames (other than `localhost`) are refused, so DNS
|
|
6
|
+
* rebinding cannot redirect traffic. Relay frames only ever supply a *path*.
|
|
7
|
+
* - Header sanitisation: untrusted forwarding headers are stripped and `Host` is rewritten.
|
|
8
|
+
* - Token bucket: second-line rate limit in front of the local server.
|
|
9
|
+
*/
|
|
10
|
+
import { isIP } from 'node:net';
|
|
11
|
+
export class GuardError extends Error {
|
|
12
|
+
status;
|
|
13
|
+
constructor(message, status = 400) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.status = status;
|
|
16
|
+
this.name = 'GuardError';
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function ipv4Octets(ip) {
|
|
20
|
+
return ip.split('.').map(Number);
|
|
21
|
+
}
|
|
22
|
+
export function isLoopback(ip) {
|
|
23
|
+
if (isIP(ip) === 4)
|
|
24
|
+
return ipv4Octets(ip)[0] === 127;
|
|
25
|
+
return ip === '::1' || ip === '0:0:0:0:0:0:0:1';
|
|
26
|
+
}
|
|
27
|
+
/** RFC 1918 IPv4 and RFC 4193 IPv6 (fc00::/7). Link-local (169.254/16, fe80::/10) is excluded: it hosts cloud metadata endpoints. */
|
|
28
|
+
export function isPrivate(ip) {
|
|
29
|
+
if (isIP(ip) === 4) {
|
|
30
|
+
const [a, b] = ipv4Octets(ip);
|
|
31
|
+
return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
32
|
+
}
|
|
33
|
+
if (isIP(ip) === 6)
|
|
34
|
+
return /^f[cd][0-9a-f]{0,2}:/i.test(ip);
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
/** Validate and lock the forwarding target. Throws GuardError for anything not loopback/private. */
|
|
38
|
+
export function lockTarget(hostInput, portInput) {
|
|
39
|
+
const port = typeof portInput === 'number' ? portInput : Number(portInput);
|
|
40
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
41
|
+
throw new GuardError(`Invalid port "${portInput}" (1-65535)`);
|
|
42
|
+
let host = String(hostInput).trim().toLowerCase();
|
|
43
|
+
if (host.startsWith('[') && host.endsWith(']'))
|
|
44
|
+
host = host.slice(1, -1);
|
|
45
|
+
if (host === 'localhost')
|
|
46
|
+
host = '127.0.0.1';
|
|
47
|
+
const family = isIP(host);
|
|
48
|
+
if (family === 0) {
|
|
49
|
+
throw new GuardError(`Refusing hostname "${hostInput}": use 127.0.0.1, ::1, localhost or an explicit private IP`);
|
|
50
|
+
}
|
|
51
|
+
if (host.startsWith('::ffff:'))
|
|
52
|
+
throw new GuardError('IPv4-mapped IPv6 addresses are not allowed; pass the IPv4 address');
|
|
53
|
+
if (!isLoopback(host) && !isPrivate(host)) {
|
|
54
|
+
throw new GuardError(`Refusing ${host}: only loopback (127.0.0.1, ::1) or private (10/8, 172.16/12, 192.168/16, fc00::/7) targets are allowed`);
|
|
55
|
+
}
|
|
56
|
+
return { host, port, authority: family === 6 ? `[${host}]:${port}` : `${host}:${port}` };
|
|
57
|
+
}
|
|
58
|
+
const MAX_PATH = 8192;
|
|
59
|
+
/**
|
|
60
|
+
* Validate a relay-supplied request path. It must be origin-form (`/…`), so it can never
|
|
61
|
+
* name another host: no scheme, no `//authority`, no backslashes, no control characters.
|
|
62
|
+
*/
|
|
63
|
+
export function safePath(path) {
|
|
64
|
+
if (typeof path !== 'string' || path.length === 0 || path.length > MAX_PATH)
|
|
65
|
+
throw new GuardError('Invalid request path');
|
|
66
|
+
if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\'))
|
|
67
|
+
throw new GuardError('Request path must be origin-form (/…)');
|
|
68
|
+
if (/[\u0000- \u007f]/.test(path))
|
|
69
|
+
throw new GuardError('Request path contains illegal characters');
|
|
70
|
+
return path;
|
|
71
|
+
}
|
|
72
|
+
const METHOD_RE = /^[A-Z]{1,16}$/;
|
|
73
|
+
export function safeMethod(method) {
|
|
74
|
+
if (typeof method !== 'string' || !METHOD_RE.test(method))
|
|
75
|
+
throw new GuardError('Invalid HTTP method');
|
|
76
|
+
return method;
|
|
77
|
+
}
|
|
78
|
+
/** Build the local WebSocket URL from the locked target, and prove the authority did not change. */
|
|
79
|
+
export function targetWsUrl(target, path) {
|
|
80
|
+
const url = `ws://${target.authority}${safePath(path)}`;
|
|
81
|
+
const parsed = new URL(url);
|
|
82
|
+
const expectedHost = target.authority.replace(/:\d+$/, '');
|
|
83
|
+
if (parsed.hostname !== expectedHost || Number(parsed.port) !== target.port) {
|
|
84
|
+
throw new GuardError('Resolved WebSocket URL escaped the locked target');
|
|
85
|
+
}
|
|
86
|
+
return url;
|
|
87
|
+
}
|
|
88
|
+
const TOKEN_RE = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
|
|
89
|
+
const STRIP = new Set([
|
|
90
|
+
// hop-by-hop
|
|
91
|
+
'connection',
|
|
92
|
+
'keep-alive',
|
|
93
|
+
'proxy-authenticate',
|
|
94
|
+
'proxy-authorization',
|
|
95
|
+
'proxy-connection',
|
|
96
|
+
'te',
|
|
97
|
+
'trailer',
|
|
98
|
+
'transfer-encoding',
|
|
99
|
+
'upgrade',
|
|
100
|
+
// rewritten / recomputed locally
|
|
101
|
+
'host',
|
|
102
|
+
'content-length',
|
|
103
|
+
// untrusted forwarding metadata
|
|
104
|
+
'forwarded',
|
|
105
|
+
'x-real-ip',
|
|
106
|
+
'x-servlink-verified',
|
|
107
|
+
]);
|
|
108
|
+
const WS_HANDSHAKE = new Set(['sec-websocket-key', 'sec-websocket-version', 'sec-websocket-extensions', 'sec-websocket-accept', 'sec-websocket-protocol']);
|
|
109
|
+
/**
|
|
110
|
+
* Sanitise relay-supplied request headers before they reach the local server: drop
|
|
111
|
+
* hop-by-hop, `X-Forwarded-*`, `X-Real-IP`, `Forwarded`; drop malformed names/values;
|
|
112
|
+
* force `Host: <host>:<port>` and add `X-Servlink-Verified: 1`.
|
|
113
|
+
*/
|
|
114
|
+
export function sanitizeHeaders(input, target, opts = {}) {
|
|
115
|
+
const out = {};
|
|
116
|
+
for (const [rawName, rawValue] of Object.entries(input ?? {})) {
|
|
117
|
+
const name = rawName.toLowerCase();
|
|
118
|
+
if (!TOKEN_RE.test(name) || STRIP.has(name) || name.startsWith('x-forwarded-'))
|
|
119
|
+
continue;
|
|
120
|
+
if (opts.websocket && WS_HANDSHAKE.has(name))
|
|
121
|
+
continue;
|
|
122
|
+
const values = (Array.isArray(rawValue) ? rawValue : [rawValue]).filter((v) => typeof v === 'string' && !/[\r\n\0]/.test(v));
|
|
123
|
+
if (values.length === 0)
|
|
124
|
+
continue;
|
|
125
|
+
out[name] = values.length === 1 ? values[0] : values;
|
|
126
|
+
}
|
|
127
|
+
out.host = target.authority;
|
|
128
|
+
out['x-servlink-verified'] = '1';
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
/** Token bucket: refills `ratePerSec` tokens/s up to `burst`. */
|
|
132
|
+
export class TokenBucket {
|
|
133
|
+
ratePerSec;
|
|
134
|
+
burst;
|
|
135
|
+
tokens;
|
|
136
|
+
last = Date.now();
|
|
137
|
+
constructor(ratePerSec, burst = Math.max(1, ratePerSec * 3)) {
|
|
138
|
+
this.ratePerSec = ratePerSec;
|
|
139
|
+
this.burst = burst;
|
|
140
|
+
this.tokens = burst;
|
|
141
|
+
}
|
|
142
|
+
take(now = Date.now()) {
|
|
143
|
+
this.tokens = Math.min(this.burst, this.tokens + ((now - this.last) / 1000) * this.ratePerSec);
|
|
144
|
+
this.last = now;
|
|
145
|
+
if (this.tokens >= 1) {
|
|
146
|
+
this.tokens -= 1;
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
return false;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
/** Upper bound of decoded bytes for a base64 string, computed without decoding it. */
|
|
153
|
+
export function base64DecodedSize(b64) {
|
|
154
|
+
const padding = b64.endsWith('==') ? 2 : b64.endsWith('=') ? 1 : 0;
|
|
155
|
+
return Math.max(0, Math.floor((b64.length * 3) / 4) - padding);
|
|
156
|
+
}
|
|
157
|
+
//# sourceMappingURL=guard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"guard.js","sourceRoot":"","sources":["../src/guard.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,UAAU,CAAC;AAGhC,MAAM,OAAO,UAAW,SAAQ,KAAK;IAGxB,MAAM;IAFjB,YACE,OAAe,EACN,MAAM,GAAG,GAAG;QAErB,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,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACnE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC;AACjE,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type KeyObject } from 'node:crypto';
|
|
2
|
+
export interface Identity {
|
|
3
|
+
version: 1;
|
|
4
|
+
node_id: string;
|
|
5
|
+
/** Raw 32-byte Ed25519 public key, hex. This is the form to register with a relay. */
|
|
6
|
+
public_key_hex: string;
|
|
7
|
+
public_key_base64: string;
|
|
8
|
+
public_key_pem: string;
|
|
9
|
+
private_key_pem: string;
|
|
10
|
+
created_at: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function defaultNodeId(): string;
|
|
13
|
+
export declare function createIdentity(nodeId?: string): Identity;
|
|
14
|
+
export declare function saveIdentity(id: Identity): void;
|
|
15
|
+
export declare function loadIdentity(): Identity | null;
|
|
16
|
+
/** POSIX only: warn when the identity file is readable by group/others. */
|
|
17
|
+
export declare function identityPermissionWarning(): string | null;
|
|
18
|
+
export declare function privateKeyOf(id: Identity): KeyObject;
|
|
19
|
+
/** Answer the relay's challenge: Ed25519 over the UTF-8 nonce string, base64-encoded. */
|
|
20
|
+
export declare function signChallenge(key: KeyObject, nonce: string): string;
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createPrivateKey, generateKeyPairSync, randomBytes, sign } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import { hostname } from 'node:os';
|
|
4
|
+
import { paths, writePrivate } from './paths.js';
|
|
5
|
+
import { NODE_ID_RE } from './protocol.js';
|
|
6
|
+
export function defaultNodeId() {
|
|
7
|
+
const host = hostname()
|
|
8
|
+
.toLowerCase()
|
|
9
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
10
|
+
.replace(/^-+|-+$/g, '')
|
|
11
|
+
.slice(0, 40);
|
|
12
|
+
return `${host || 'node'}-${randomBytes(4).toString('hex')}`;
|
|
13
|
+
}
|
|
14
|
+
export function createIdentity(nodeId = defaultNodeId()) {
|
|
15
|
+
if (!NODE_ID_RE.test(nodeId)) {
|
|
16
|
+
throw new Error('node_id must be 3-128 chars: letters, digits, . _ : - (and start with a letter or digit)');
|
|
17
|
+
}
|
|
18
|
+
const { privateKey, publicKey } = generateKeyPairSync('ed25519');
|
|
19
|
+
const raw = Buffer.from(publicKey.export({ format: 'der', type: 'spki' })).subarray(-32);
|
|
20
|
+
return {
|
|
21
|
+
version: 1,
|
|
22
|
+
node_id: nodeId,
|
|
23
|
+
public_key_hex: raw.toString('hex'),
|
|
24
|
+
public_key_base64: raw.toString('base64'),
|
|
25
|
+
public_key_pem: publicKey.export({ format: 'pem', type: 'spki' }).toString(),
|
|
26
|
+
private_key_pem: privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(),
|
|
27
|
+
created_at: new Date().toISOString(),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
export function saveIdentity(id) {
|
|
31
|
+
writePrivate(paths.identity, `${JSON.stringify(id, null, 2)}\n`);
|
|
32
|
+
}
|
|
33
|
+
export function loadIdentity() {
|
|
34
|
+
if (!existsSync(paths.identity))
|
|
35
|
+
return null;
|
|
36
|
+
const parsed = JSON.parse(readFileSync(paths.identity, 'utf8'));
|
|
37
|
+
if (!parsed.node_id || !parsed.private_key_pem || !parsed.public_key_hex) {
|
|
38
|
+
throw new Error(`${paths.identity} is incomplete; re-run "slink init --force"`);
|
|
39
|
+
}
|
|
40
|
+
return parsed;
|
|
41
|
+
}
|
|
42
|
+
/** POSIX only: warn when the identity file is readable by group/others. */
|
|
43
|
+
export function identityPermissionWarning() {
|
|
44
|
+
if (process.platform === 'win32' || !existsSync(paths.identity))
|
|
45
|
+
return null;
|
|
46
|
+
const mode = statSync(paths.identity).mode & 0o777;
|
|
47
|
+
return mode & 0o077 ? `${paths.identity} has mode ${mode.toString(8)}; run: chmod 600 ${paths.identity}` : null;
|
|
48
|
+
}
|
|
49
|
+
export function privateKeyOf(id) {
|
|
50
|
+
return createPrivateKey(id.private_key_pem);
|
|
51
|
+
}
|
|
52
|
+
/** Answer the relay's challenge: Ed25519 over the UTF-8 nonce string, base64-encoded. */
|
|
53
|
+
export function signChallenge(key, nonce) {
|
|
54
|
+
return sign(null, Buffer.from(nonce, 'utf8'), key).toString('base64');
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=identity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.js","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,WAAW,EAAE,IAAI,EAAkB,MAAM,aAAa,CAAC;AACvG,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAa3C,MAAM,UAAU,aAAa;IAC3B,MAAM,IAAI,GAAG,QAAQ,EAAE;SACpB,WAAW,EAAE;SACb,OAAO,CAAC,cAAc,EAAE,GAAG,CAAC;SAC5B,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC;SACvB,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;IAChB,OAAO,GAAG,IAAI,IAAI,MAAM,IAAI,WAAW,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,cAAc,CAAC,MAAM,GAAW,aAAa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C,KAAK,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAa,CAAC;IAC5E,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,CAAC,MAAM,CAAC,eAAe,IAAI,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;QACzE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,CAAC,QAAQ,6CAA6C,CAAC,CAAC;IAClF,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,yBAAyB;IACvC,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,QAAQ,CAAC;QAAE,OAAO,IAAI,CAAC;IAC7E,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC;IACnD,OAAO,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,aAAa,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,oBAAoB,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAClH,CAAC;AAED,MAAM,UAAU,YAAY,CAAC,EAAY;IACvC,OAAO,gBAAgB,CAAC,EAAE,CAAC,eAAe,CAAC,CAAC;AAC9C,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,aAAa,CAAC,GAAc,EAAE,KAAa;IACzD,OAAO,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AACxE,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { SlinkTunnel, type TunnelOptions, type TunnelState } from './tunnel.js';
|
|
2
|
+
export { lockTarget, safePath, sanitizeHeaders, targetWsUrl, TokenBucket, GuardError, type Target } from './guard.js';
|
|
3
|
+
export { createIdentity, loadIdentity, saveIdentity, signChallenge, privateKeyOf, type Identity } from './identity.js';
|
|
4
|
+
export { WakeManager, waitForPort, isPortOpen } from './wake.js';
|
|
5
|
+
export { RequestLog, formatLogLine, sanitizeLogPath } from './logs.js';
|
|
6
|
+
export * from './protocol.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { SlinkTunnel } from './tunnel.js';
|
|
2
|
+
export { lockTarget, safePath, sanitizeHeaders, targetWsUrl, TokenBucket, GuardError } from './guard.js';
|
|
3
|
+
export { createIdentity, loadIdentity, saveIdentity, signChallenge, privateKeyOf } from './identity.js';
|
|
4
|
+
export { WakeManager, waitForPort, isPortOpen } from './wake.js';
|
|
5
|
+
export { RequestLog, formatLogLine, sanitizeLogPath } from './logs.js';
|
|
6
|
+
export * from './protocol.js';
|
|
7
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAwC,MAAM,aAAa,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAe,MAAM,YAAY,CAAC;AACtH,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,YAAY,EAAiB,MAAM,eAAe,CAAC;AACvH,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACvE,cAAc,eAAe,CAAC"}
|
package/dist/logs.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface RequestLogEntry {
|
|
2
|
+
leaseId?: string | null;
|
|
3
|
+
method: string;
|
|
4
|
+
path: string;
|
|
5
|
+
status: number | string;
|
|
6
|
+
ms: number;
|
|
7
|
+
at?: Date;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Sanitise a path for logging: query strings are dropped (they routinely carry tokens),
|
|
11
|
+
* control characters are escaped to prevent log injection, length is capped.
|
|
12
|
+
*/
|
|
13
|
+
export declare function sanitizeLogPath(path: string): string;
|
|
14
|
+
/** `[timestamp] [lease_id] METHOD /path -> STATUS (latency_ms)`. Bodies and cookies are never passed in. */
|
|
15
|
+
export declare function formatLogLine(e: RequestLogEntry): string;
|
|
16
|
+
/** Append-only request log with size-based rotation (requests.log → .1 → .2 → .3). */
|
|
17
|
+
export declare class RequestLog {
|
|
18
|
+
readonly file: string;
|
|
19
|
+
private readonly maxBytes;
|
|
20
|
+
private readonly keep;
|
|
21
|
+
private size;
|
|
22
|
+
constructor(file?: string, maxBytes?: number, keep?: number);
|
|
23
|
+
write(entry: RequestLogEntry): void;
|
|
24
|
+
private rotate;
|
|
25
|
+
}
|
|
26
|
+
/** Last `n` lines of a file (reads from the end in blocks; fine for multi-MB logs). */
|
|
27
|
+
export declare function tailLines(file: string, n: number): {
|
|
28
|
+
lines: string[];
|
|
29
|
+
size: number;
|
|
30
|
+
};
|
|
31
|
+
/** Follow a log file, surviving rotation/truncation. Returns a stop function. */
|
|
32
|
+
export declare function followFile(file: string, fromOffset: number, onLine: (line: string) => void, intervalMs?: number): () => void;
|
package/dist/logs.js
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { appendFileSync, closeSync, existsSync, openSync, readSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
2
|
+
import { ensureHome, paths } from './paths.js';
|
|
3
|
+
/**
|
|
4
|
+
* Sanitise a path for logging: query strings are dropped (they routinely carry tokens),
|
|
5
|
+
* control characters are escaped to prevent log injection, length is capped.
|
|
6
|
+
*/
|
|
7
|
+
export function sanitizeLogPath(path) {
|
|
8
|
+
const q = path.indexOf('?');
|
|
9
|
+
const base = q === -1 ? path : `${path.slice(0, q)}?…`;
|
|
10
|
+
const clean = base.replace(/[\u0000-\u001f\u007f]/g, (c) => `\\x${c.charCodeAt(0).toString(16).padStart(2, '0')}`);
|
|
11
|
+
return clean.length > 512 ? `${clean.slice(0, 511)}…` : clean;
|
|
12
|
+
}
|
|
13
|
+
const LEASE_RE = /^[A-Za-z0-9._-]{1,64}$/;
|
|
14
|
+
/** `[timestamp] [lease_id] METHOD /path -> STATUS (latency_ms)`. Bodies and cookies are never passed in. */
|
|
15
|
+
export function formatLogLine(e) {
|
|
16
|
+
const lease = e.leaseId && LEASE_RE.test(e.leaseId) ? e.leaseId : '-';
|
|
17
|
+
const method = /^[A-Z]{1,16}$/.test(e.method) ? e.method : '?';
|
|
18
|
+
return `[${(e.at ?? new Date()).toISOString()}] [${lease}] ${method} ${sanitizeLogPath(e.path)} -> ${e.status} (${Math.max(0, Math.round(e.ms))}ms)`;
|
|
19
|
+
}
|
|
20
|
+
/** Append-only request log with size-based rotation (requests.log → .1 → .2 → .3). */
|
|
21
|
+
export class RequestLog {
|
|
22
|
+
file;
|
|
23
|
+
maxBytes;
|
|
24
|
+
keep;
|
|
25
|
+
size = 0;
|
|
26
|
+
constructor(file = paths.requestLog, maxBytes = 5 * 1024 * 1024, keep = 3) {
|
|
27
|
+
this.file = file;
|
|
28
|
+
this.maxBytes = maxBytes;
|
|
29
|
+
this.keep = keep;
|
|
30
|
+
ensureHome();
|
|
31
|
+
this.size = existsSync(file) ? statSync(file).size : 0;
|
|
32
|
+
}
|
|
33
|
+
write(entry) {
|
|
34
|
+
const line = `${formatLogLine(entry)}\n`;
|
|
35
|
+
try {
|
|
36
|
+
if (this.size + line.length > this.maxBytes)
|
|
37
|
+
this.rotate();
|
|
38
|
+
appendFileSync(this.file, line, { mode: 0o600 });
|
|
39
|
+
this.size += Buffer.byteLength(line);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
/* logging must never take the tunnel down */
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
rotate() {
|
|
46
|
+
for (let i = this.keep; i >= 1; i--) {
|
|
47
|
+
const from = i === 1 ? this.file : `${this.file}.${i - 1}`;
|
|
48
|
+
const to = `${this.file}.${i}`;
|
|
49
|
+
if (!existsSync(from))
|
|
50
|
+
continue;
|
|
51
|
+
if (existsSync(to))
|
|
52
|
+
rmSync(to);
|
|
53
|
+
renameSync(from, to);
|
|
54
|
+
}
|
|
55
|
+
this.size = 0;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** Last `n` lines of a file (reads from the end in blocks; fine for multi-MB logs). */
|
|
59
|
+
export function tailLines(file, n) {
|
|
60
|
+
if (!existsSync(file))
|
|
61
|
+
return { lines: [], size: 0 };
|
|
62
|
+
const size = statSync(file).size;
|
|
63
|
+
const fd = openSync(file, 'r');
|
|
64
|
+
try {
|
|
65
|
+
let pos = size;
|
|
66
|
+
let text = '';
|
|
67
|
+
const block = Buffer.alloc(64 * 1024);
|
|
68
|
+
while (pos > 0 && text.split('\n').length <= n + 1) {
|
|
69
|
+
const len = Math.min(block.length, pos);
|
|
70
|
+
pos -= len;
|
|
71
|
+
readSync(fd, block, 0, len, pos);
|
|
72
|
+
text = block.subarray(0, len).toString('utf8') + text;
|
|
73
|
+
}
|
|
74
|
+
const lines = text.split('\n').filter(Boolean);
|
|
75
|
+
return { lines: lines.slice(-n), size };
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
closeSync(fd);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Follow a log file, surviving rotation/truncation. Returns a stop function. */
|
|
82
|
+
export function followFile(file, fromOffset, onLine, intervalMs = 400) {
|
|
83
|
+
let offset = fromOffset;
|
|
84
|
+
let carry = '';
|
|
85
|
+
const timer = setInterval(() => {
|
|
86
|
+
if (!existsSync(file))
|
|
87
|
+
return;
|
|
88
|
+
const size = statSync(file).size;
|
|
89
|
+
if (size < offset)
|
|
90
|
+
offset = 0; // rotated or truncated
|
|
91
|
+
if (size === offset)
|
|
92
|
+
return;
|
|
93
|
+
const fd = openSync(file, 'r');
|
|
94
|
+
try {
|
|
95
|
+
const buf = Buffer.alloc(size - offset);
|
|
96
|
+
readSync(fd, buf, 0, buf.length, offset);
|
|
97
|
+
offset = size;
|
|
98
|
+
const parts = (carry + buf.toString('utf8')).split('\n');
|
|
99
|
+
carry = parts.pop() ?? '';
|
|
100
|
+
for (const line of parts)
|
|
101
|
+
if (line)
|
|
102
|
+
onLine(line);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
closeSync(fd);
|
|
106
|
+
}
|
|
107
|
+
}, intervalMs);
|
|
108
|
+
return () => clearInterval(timer);
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=logs.js.map
|
package/dist/logs.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logs.js","sourceRoot":"","sources":["../src/logs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAClH,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AAW/C;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAC,IAAY;IAC1C,MAAM,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5B,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC;IACvD,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,E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,IAAI,MAAM,GAAG,UAAU,CAAC;IACxB,IAAI,KAAK,GAAG,EAAE,CAAC;IACf,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE;QAC7B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;YAAE,OAAO;QAC9B,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC;QACjC,IAAI,IAAI,GAAG,MAAM;YAAE,MAAM,GAAG,CAAC,CAAC,CAAC,uBAAuB;QACtD,IAAI,IAAI,KAAK,MAAM;YAAE,OAAO;QAC5B,MAAM,EAAE,GAAG,QAAQ,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QAC/B,IAAI,CAAC;YACH,MAAM,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,GAAG,MAAM,CAAC,CAAC;YACxC,QAAQ,CAAC,EAAE,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;YACzC,MAAM,GAAG,IAAI,CAAC;YACd,MAAM,KAAK,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACzD,KAAK,GAAG,KAAK,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC;YAC1B,KAAK,MAAM,IAAI,IAAI,KAAK;gBAAE,IAAI,IAAI;oBAAE,MAAM,CAAC,IAAI,CAAC,CAAC;QACnD,CAAC;gBAAS,CAAC;YACT,SAAS,CAAC,EAAE,CAAC,CAAC;QAChB,CAAC;IACH,CAAC,EAAE,UAAU,CAAC,CAAC;IACf,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC"}
|
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Root of slink's local state. `SERVLINK_HOME` overrides it (tests, multiple identities). */
|
|
2
|
+
export declare function servlinkHome(): string;
|
|
3
|
+
export declare const paths: {
|
|
4
|
+
readonly home: string;
|
|
5
|
+
readonly identity: string;
|
|
6
|
+
readonly config: string;
|
|
7
|
+
readonly daemon: string;
|
|
8
|
+
readonly logDir: string;
|
|
9
|
+
readonly requestLog: string;
|
|
10
|
+
readonly wakeLog: string;
|
|
11
|
+
};
|
|
12
|
+
export declare function ensureHome(): void;
|
|
13
|
+
/** Atomically write a file readable only by the current user (0600). */
|
|
14
|
+
export declare function writePrivate(file: string, content: string): void;
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
/** Root of slink's local state. `SERVLINK_HOME` overrides it (tests, multiple identities). */
|
|
5
|
+
export function servlinkHome() {
|
|
6
|
+
return process.env.SERVLINK_HOME || join(homedir(), '.servlink');
|
|
7
|
+
}
|
|
8
|
+
export const paths = {
|
|
9
|
+
get home() {
|
|
10
|
+
return servlinkHome();
|
|
11
|
+
},
|
|
12
|
+
get identity() {
|
|
13
|
+
return join(servlinkHome(), 'identity.json');
|
|
14
|
+
},
|
|
15
|
+
get config() {
|
|
16
|
+
return join(servlinkHome(), 'config.json');
|
|
17
|
+
},
|
|
18
|
+
get daemon() {
|
|
19
|
+
return join(servlinkHome(), 'daemon.json');
|
|
20
|
+
},
|
|
21
|
+
get logDir() {
|
|
22
|
+
return join(servlinkHome(), 'logs');
|
|
23
|
+
},
|
|
24
|
+
get requestLog() {
|
|
25
|
+
return join(servlinkHome(), 'logs', 'requests.log');
|
|
26
|
+
},
|
|
27
|
+
get wakeLog() {
|
|
28
|
+
return join(servlinkHome(), 'logs', 'wake.log');
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
export function ensureHome() {
|
|
32
|
+
mkdirSync(paths.home, { recursive: true, mode: 0o700 });
|
|
33
|
+
mkdirSync(paths.logDir, { recursive: true, mode: 0o700 });
|
|
34
|
+
}
|
|
35
|
+
/** Atomically write a file readable only by the current user (0600). */
|
|
36
|
+
export function writePrivate(file, content) {
|
|
37
|
+
ensureHome();
|
|
38
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
39
|
+
writeFileSync(tmp, content, { mode: 0o600 });
|
|
40
|
+
try {
|
|
41
|
+
chmodSync(tmp, 0o600);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
/* chmod is a no-op on some filesystems (e.g. Windows) */
|
|
45
|
+
}
|
|
46
|
+
renameSync(tmp, file);
|
|
47
|
+
}
|
|
48
|
+
//# sourceMappingURL=paths.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"paths.js","sourceRoot":"","sources":["../src/paths.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,8FAA8F;AAC9F,MAAM,UAAU,YAAY;IAC1B,OAAO,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,IAAI,CAAC,OAAO,EAAE,EAAE,WAAW,CAAC,CAAC;AACnE,CAAC;AAED,MAAM,CAAC,MAAM,KAAK,GAAG;IACnB,IAAI,IAAI;QACN,OAAO,YAAY,EAAE,CAAC;IACxB,CAAC;IACD,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,eAAe,CAAC,CAAC;IAC/C,CAAC;IACD,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,aAAa,CAAC,CAAC;IAC7C,CAAC;IACD,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,aAAa,CAAC,CAAC;IAC7C,CAAC;IACD,IAAI,MAAM;QACR,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,MAAM,CAAC,CAAC;IACtC,CAAC;IACD,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,MAAM,EAAE,cAAc,CAAC,CAAC;IACtD,CAAC;IACD,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,YAAY,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;IAClD,CAAC;CACF,CAAC;AAEF,MAAM,UAAU,UAAU;IACxB,SAAS,CAAC,KAAK,CAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IACxD,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;AAC5D,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,YAAY,CAAC,IAAY,EAAE,OAAe;IACxD,UAAU,EAAE,CAAC;IACb,MAAM,GAAG,GAAG,GAAG,IAAI,IAAI,OAAO,CAAC,GAAG,MAAM,CAAC;IACzC,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC;IAC7C,IAAI,CAAC;QACH,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxB,CAAC;IAAC,MAAM,CAAC;QACP,yDAAyD;IAC3D,CAAC;IACD,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AACxB,CAAC"}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* slink <-> relay tunnel wire protocol: JSON text frames over one outbound WebSocket.
|
|
3
|
+
* Any relay that speaks these frames works; the README documents them for implementers.
|
|
4
|
+
*
|
|
5
|
+
* Handshake
|
|
6
|
+
* S→C { type: "challenge", nonce: <64 hex chars>, server_time }
|
|
7
|
+
* C→S { type: "auth", node_id, signature } // Ed25519 over the UTF-8 nonce string, base64
|
|
8
|
+
* S→C { type: "auth_ok", node_id } | { type: "auth_error", reason } (then close 4401)
|
|
9
|
+
*
|
|
10
|
+
* HTTP
|
|
11
|
+
* S→C { type: "http_request", id, method, path, headers, body?, lease_id? } // body = base64
|
|
12
|
+
* S→C { type: "http_cancel", id }
|
|
13
|
+
* C→S { type: "http_response", id, status, headers, body? } // single shot
|
|
14
|
+
* C→S { type: "http_response_start", id, status, headers } // or streamed
|
|
15
|
+
* C→S { type: "http_response_chunk", id, data } // base64
|
|
16
|
+
* C→S { type: "http_response_end", id }
|
|
17
|
+
* C→S { type: "http_error", id, message }
|
|
18
|
+
*
|
|
19
|
+
* WebSocket (multiplexed by stream id)
|
|
20
|
+
* S→C { type: "ws_open", id, path, headers, lease_id? }
|
|
21
|
+
* C→S { type: "ws_opened", id } | { type: "ws_error", id, message }
|
|
22
|
+
* both { type: "ws_message", id, data, binary } // base64 when binary
|
|
23
|
+
* both { type: "ws_close", id, code?, reason? }
|
|
24
|
+
*
|
|
25
|
+
* Liveness: WebSocket ping/pong in both directions; app-level { type: "ping" } → { type: "pong" }.
|
|
26
|
+
*/
|
|
27
|
+
export type HeaderMap = Record<string, string | string[]>;
|
|
28
|
+
/** Frames the relay sends to slink. */
|
|
29
|
+
export type RelayFrame = {
|
|
30
|
+
type: 'challenge';
|
|
31
|
+
nonce: string;
|
|
32
|
+
server_time: number;
|
|
33
|
+
} | {
|
|
34
|
+
type: 'auth_ok';
|
|
35
|
+
node_id: string;
|
|
36
|
+
} | {
|
|
37
|
+
type: 'auth_error';
|
|
38
|
+
reason: string;
|
|
39
|
+
} | {
|
|
40
|
+
type: 'pong';
|
|
41
|
+
} | {
|
|
42
|
+
type: 'http_request';
|
|
43
|
+
id: string;
|
|
44
|
+
method: string;
|
|
45
|
+
path: string;
|
|
46
|
+
headers: HeaderMap;
|
|
47
|
+
body?: string;
|
|
48
|
+
lease_id?: string;
|
|
49
|
+
} | {
|
|
50
|
+
type: 'http_cancel';
|
|
51
|
+
id: string;
|
|
52
|
+
} | {
|
|
53
|
+
type: 'ws_open';
|
|
54
|
+
id: string;
|
|
55
|
+
path: string;
|
|
56
|
+
headers: HeaderMap;
|
|
57
|
+
lease_id?: string;
|
|
58
|
+
} | {
|
|
59
|
+
type: 'ws_message';
|
|
60
|
+
id: string;
|
|
61
|
+
data: string;
|
|
62
|
+
binary: boolean;
|
|
63
|
+
} | {
|
|
64
|
+
type: 'ws_close';
|
|
65
|
+
id: string;
|
|
66
|
+
code?: number;
|
|
67
|
+
reason?: string;
|
|
68
|
+
};
|
|
69
|
+
/** Frames slink sends to the relay. */
|
|
70
|
+
export type NodeFrame = {
|
|
71
|
+
type: 'auth';
|
|
72
|
+
node_id: string;
|
|
73
|
+
signature: string;
|
|
74
|
+
} | {
|
|
75
|
+
type: 'ping';
|
|
76
|
+
} | {
|
|
77
|
+
type: 'http_response';
|
|
78
|
+
id: string;
|
|
79
|
+
status: number;
|
|
80
|
+
headers?: HeaderMap;
|
|
81
|
+
body?: string;
|
|
82
|
+
} | {
|
|
83
|
+
type: 'http_response_start';
|
|
84
|
+
id: string;
|
|
85
|
+
status: number;
|
|
86
|
+
headers?: HeaderMap;
|
|
87
|
+
} | {
|
|
88
|
+
type: 'http_response_chunk';
|
|
89
|
+
id: string;
|
|
90
|
+
data: string;
|
|
91
|
+
} | {
|
|
92
|
+
type: 'http_response_end';
|
|
93
|
+
id: string;
|
|
94
|
+
} | {
|
|
95
|
+
type: 'http_error';
|
|
96
|
+
id: string;
|
|
97
|
+
message?: string;
|
|
98
|
+
} | {
|
|
99
|
+
type: 'ws_opened';
|
|
100
|
+
id: string;
|
|
101
|
+
} | {
|
|
102
|
+
type: 'ws_error';
|
|
103
|
+
id: string;
|
|
104
|
+
message?: string;
|
|
105
|
+
} | {
|
|
106
|
+
type: 'ws_message';
|
|
107
|
+
id: string;
|
|
108
|
+
data: string;
|
|
109
|
+
binary?: boolean;
|
|
110
|
+
} | {
|
|
111
|
+
type: 'ws_close';
|
|
112
|
+
id: string;
|
|
113
|
+
code?: number;
|
|
114
|
+
reason?: string;
|
|
115
|
+
};
|
|
116
|
+
/** Close codes the relay uses on the tunnel socket. */
|
|
117
|
+
export declare const RelayClose: {
|
|
118
|
+
readonly PROTOCOL: 4400;
|
|
119
|
+
readonly AUTH_FAILED: 4401;
|
|
120
|
+
readonly AUTH_TIMEOUT: 4408;
|
|
121
|
+
readonly SUPERSEDED: 4409;
|
|
122
|
+
readonly UNBOUND: 4410;
|
|
123
|
+
};
|
|
124
|
+
/** Allowed node_id shape; relays should enforce the same rule when registering a node. */
|
|
125
|
+
export declare const NODE_ID_RE: RegExp;
|
|
126
|
+
/**
|
|
127
|
+
* Parse and structurally validate a relay frame. Anything malformed returns null and is
|
|
128
|
+
* dropped. Nothing in a frame can choose where slink connects: only path/method/headers/body.
|
|
129
|
+
*/
|
|
130
|
+
export declare function parseRelayFrame(raw: string): RelayFrame | null;
|