servlink 0.0.0-stage → 1.0.2

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.
@@ -0,0 +1,85 @@
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
+ /** Close codes the relay uses on the tunnel socket. */
28
+ export const RelayClose = {
29
+ PROTOCOL: 4400,
30
+ AUTH_FAILED: 4401,
31
+ AUTH_TIMEOUT: 4408,
32
+ SUPERSEDED: 4409,
33
+ UNBOUND: 4410,
34
+ };
35
+ /** Allowed node_id shape; relays should enforce the same rule when registering a node. */
36
+ export const NODE_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,127}$/;
37
+ const STREAM_ID_RE = /^[A-Za-z0-9-]{1,64}$/;
38
+ /**
39
+ * Parse and structurally validate a relay frame. Anything malformed returns null and is
40
+ * dropped. Nothing in a frame can choose where slink connects: only path/method/headers/body.
41
+ */
42
+ export function parseRelayFrame(raw) {
43
+ let v;
44
+ try {
45
+ v = JSON.parse(raw);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ if (!v || typeof v !== 'object' || Array.isArray(v))
51
+ return null;
52
+ const f = v;
53
+ const str = (k) => typeof f[k] === 'string';
54
+ const id = () => typeof f.id === 'string' && STREAM_ID_RE.test(f.id);
55
+ const headers = () => f.headers === undefined || (typeof f.headers === 'object' && f.headers !== null && !Array.isArray(f.headers));
56
+ switch (f.type) {
57
+ case 'challenge':
58
+ return str('nonce') && /^[0-9a-f]{64}$/i.test(f.nonce) ? f : null;
59
+ case 'auth_ok':
60
+ case 'auth_error':
61
+ case 'pong':
62
+ return f;
63
+ case 'http_request':
64
+ if (!id() || !str('method') || !str('path') || !headers())
65
+ return null;
66
+ if (f.body !== undefined && typeof f.body !== 'string')
67
+ return null;
68
+ if (f.lease_id !== undefined && typeof f.lease_id !== 'string')
69
+ return null;
70
+ return { ...f, headers: (f.headers ?? {}) };
71
+ case 'http_cancel':
72
+ return id() ? f : null;
73
+ case 'ws_open':
74
+ if (!id() || !str('path') || !headers())
75
+ return null;
76
+ return { ...f, headers: (f.headers ?? {}) };
77
+ case 'ws_message':
78
+ return id() && str('data') ? { ...f, binary: f.binary === true } : null;
79
+ case 'ws_close':
80
+ return id() ? f : null;
81
+ default:
82
+ return null;
83
+ }
84
+ }
85
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../src/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AA8BH,uDAAuD;AACvD,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,QAAQ,EAAE,IAAI;IACd,WAAW,EAAE,IAAI;IACjB,YAAY,EAAE,IAAI;IAClB,UAAU,EAAE,IAAI;IAChB,OAAO,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 @@
1
+ export interface SavedConfig {
2
+ host: string;
3
+ port: number;
4
+ relay: string;
5
+ maxRps: number;
6
+ maxBodyMb: number;
7
+ wakeCmd?: string;
8
+ sleepCmd?: string;
9
+ idleMinutes?: number;
10
+ }
11
+ export declare const DEFAULTS: {
12
+ readonly host: '127.0.0.1';
13
+ readonly maxRps: 30;
14
+ readonly maxBodyMb: 5;
15
+ readonly idleMinutes: 15;
16
+ };
17
+ export declare function loadConfig(): SavedConfig | null;
18
+ export declare function saveConfig(cfg: SavedConfig): void;
19
+ export interface DaemonState {
20
+ pid: number;
21
+ started_at: string;
22
+ node_id: string;
23
+ relay: string;
24
+ target: string;
25
+ state: string;
26
+ detail?: string;
27
+ updated_at: string;
28
+ }
29
+ export declare function writeDaemonState(s: Omit<DaemonState, 'updated_at'>): void;
30
+ export declare function clearDaemonState(pid?: number): void;
31
+ export declare function readDaemonState(): DaemonState | null;
32
+ export declare function isProcessAlive(pid: number): boolean;
33
+ /** The running `slink connect` daemon, if any (stale state files are ignored). */
34
+ export declare function activeDaemon(): DaemonState | null;
package/dist/state.js ADDED
@@ -0,0 +1,50 @@
1
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import { paths, writePrivate } from './paths.js';
3
+ export const DEFAULTS = {
4
+ host: '127.0.0.1',
5
+ maxRps: 30,
6
+ maxBodyMb: 5,
7
+ idleMinutes: 15,
8
+ };
9
+ export function loadConfig() {
10
+ try {
11
+ return existsSync(paths.config) ? JSON.parse(readFileSync(paths.config, 'utf8')) : null;
12
+ }
13
+ catch {
14
+ return null;
15
+ }
16
+ }
17
+ export function saveConfig(cfg) {
18
+ writePrivate(paths.config, `${JSON.stringify(cfg, null, 2)}\n`);
19
+ }
20
+ export function writeDaemonState(s) {
21
+ writePrivate(paths.daemon, `${JSON.stringify({ ...s, updated_at: new Date().toISOString() }, null, 2)}\n`);
22
+ }
23
+ export function clearDaemonState(pid = process.pid) {
24
+ const s = readDaemonState();
25
+ if (s && s.pid === pid)
26
+ rmSync(paths.daemon, { force: true });
27
+ }
28
+ export function readDaemonState() {
29
+ try {
30
+ return existsSync(paths.daemon) ? JSON.parse(readFileSync(paths.daemon, 'utf8')) : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ export function isProcessAlive(pid) {
37
+ try {
38
+ process.kill(pid, 0);
39
+ return true;
40
+ }
41
+ catch (err) {
42
+ return err.code === 'EPERM';
43
+ }
44
+ }
45
+ /** The running `slink connect` daemon, if any (stale state files are ignored). */
46
+ export function activeDaemon() {
47
+ const s = readDaemonState();
48
+ return s && isProcessAlive(s.pid) ? s : null;
49
+ }
50
+ //# sourceMappingURL=state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../src/state.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAajD,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,IAAI,EAAE,WAAW;IACjB,MAAM,EAAE,EAAE;IACV,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,EAAE;CACP,CAAC;AAEX,MAAM,UAAU,UAAU;IACxB,IAAI,CAAC;QACH,OAAO,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAE,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAiB,CAAC,CAAC,CAAC,IAAI,CAAC;IAC3G,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,GAAgB;IACzC,YAAY,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC;AAClE,CAAC;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IAAI,CAAC;AAC/C,CAAC"}
@@ -0,0 +1,61 @@
1
+ import type { KeyObject } from 'node:crypto';
2
+ import { type Target } from './guard.js';
3
+ import type { RequestLog } from './logs.js';
4
+ import type { WakeManager } from './wake.js';
5
+ export type TunnelState = 'connecting' | 'authenticating' | 'online' | 'reconnecting' | 'stopped';
6
+ export interface TunnelOptions {
7
+ relay: string;
8
+ nodeId: string;
9
+ privateKey: KeyObject;
10
+ /** Locked at startup; relay frames can never change it. */
11
+ target: Target;
12
+ maxRps: number;
13
+ maxBodyMb: number;
14
+ wake?: WakeManager;
15
+ requestLog?: RequestLog;
16
+ /** Hard limit for connecting + receiving response headers from the local server. */
17
+ localTimeoutMs?: number;
18
+ /** Idle limit for a response stream once headers have arrived. */
19
+ streamIdleMs?: number;
20
+ heartbeatMs?: number;
21
+ backoffBaseMs?: number;
22
+ backoffMaxMs?: number;
23
+ maxConcurrent?: number;
24
+ onState?: (state: TunnelState, detail?: string) => void;
25
+ log?: (msg: string) => void;
26
+ }
27
+ export declare class SlinkTunnel {
28
+ private ws;
29
+ private state;
30
+ private attempt;
31
+ private stopped;
32
+ private heartbeat;
33
+ private reconnectTimer;
34
+ private awaitingPong;
35
+ private readonly http;
36
+ private readonly sockets;
37
+ private readonly bucket;
38
+ private readonly maxBodyBytes;
39
+ private readonly o;
40
+ /** Count of authenticated sessions (observable for tests / status). */
41
+ connections: number;
42
+ constructor(opts: TunnelOptions);
43
+ get currentState(): TunnelState;
44
+ start(): void;
45
+ stop(): void;
46
+ private setState;
47
+ private connect;
48
+ private scheduleReconnect;
49
+ private startHeartbeat;
50
+ private stopHeartbeat;
51
+ private teardownStreams;
52
+ private send;
53
+ private onFrame;
54
+ private handleHttp;
55
+ /** One attempt against the local server. Resolves with the status once the response has fully streamed. */
56
+ private forward;
57
+ /** Pause the local response while the tunnel socket has too much unsent data. */
58
+ private applyBackpressure;
59
+ private closeStream;
60
+ private handleWsOpen;
61
+ }