asyx 0.5.9 → 0.6.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/README.md +71 -9
- package/SECURITY.md +5 -3
- package/package.json +13 -23
- package/src/commands/name.js +23 -0
- package/src/commands/reject-messages.js +54 -0
- package/src/commands/setup.js +98 -102
- package/src/commands/tunnel.js +279 -2425
- package/src/lib/naming.js +81 -0
- package/src/main.js +9 -1
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.d.ts +260 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneClient.js +1088 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.d.ts +79 -0
- package/vendor/tunnel-core/dist/control-plane/MqttControlPlaneTransport.js +138 -0
- package/vendor/tunnel-core/dist/control-plane/session.d.ts +50 -0
- package/vendor/tunnel-core/dist/control-plane/session.js +115 -0
- package/vendor/tunnel-core/dist/errors.d.ts +49 -0
- package/vendor/tunnel-core/dist/errors.js +53 -0
- package/vendor/tunnel-core/dist/flows/http.d.ts +50 -0
- package/vendor/tunnel-core/dist/flows/http.js +585 -0
- package/vendor/tunnel-core/dist/flows/tcp.d.ts +60 -0
- package/vendor/tunnel-core/dist/flows/tcp.js +546 -0
- package/vendor/tunnel-core/dist/flows/udp.d.ts +41 -0
- package/vendor/tunnel-core/dist/flows/udp.js +376 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.d.ts +2 -0
- package/vendor/tunnel-core/dist/lib/adapt-logger.js +6 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.d.ts +13 -0
- package/vendor/tunnel-core/dist/lib/fingerprint.js +95 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.d.ts +27 -0
- package/vendor/tunnel-core/dist/lib/jwt-verifier.js +230 -0
- package/vendor/tunnel-core/dist/lib/logger.d.ts +9 -0
- package/vendor/tunnel-core/dist/lib/logger.js +58 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.d.ts +16 -0
- package/vendor/tunnel-core/dist/lib/refresh-helpers.js +66 -0
- package/vendor/tunnel-core/dist/lifecycle.d.ts +24 -0
- package/vendor/tunnel-core/dist/lifecycle.js +29 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.d.ts +56 -0
- package/vendor/tunnel-core/dist/mqtt/awaiter-map.js +227 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.d.ts +58 -0
- package/vendor/tunnel-core/dist/mqtt/events/handlers.js +250 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.d.ts +1 -0
- package/vendor/tunnel-core/dist/mqtt/events/index.js +191 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.d.ts +498 -0
- package/vendor/tunnel-core/dist/mqtt/events/schemas.js +51 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.d.ts +63 -0
- package/vendor/tunnel-core/dist/mqtt/ingress.js +170 -0
- package/vendor/tunnel-core/dist/state/assignment.d.ts +122 -0
- package/vendor/tunnel-core/dist/state/assignment.js +322 -0
- package/vendor/tunnel-core/dist/state/instance-registry.d.ts +88 -0
- package/{src → vendor/tunnel-core/dist}/state/instance-registry.js +38 -53
- package/vendor/tunnel-core/dist/tcp-v1/framing.d.ts +43 -0
- package/vendor/tunnel-core/dist/tcp-v1/framing.js +157 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.d.ts +137 -0
- package/vendor/tunnel-core/dist/tunnel/http-tunnel.js +1591 -0
- package/vendor/tunnel-core/dist/tunnel/httpws-constants.d.ts +13 -0
- package/{src → vendor/tunnel-core/dist}/tunnel/httpws-constants.js +5 -7
- package/vendor/tunnel-core/dist/tunnel/reconnect.d.ts +76 -0
- package/vendor/tunnel-core/dist/tunnel/reconnect.js +183 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.d.ts +40 -0
- package/vendor/tunnel-core/dist/tunnel/request-sink.js +39 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.d.ts +89 -0
- package/vendor/tunnel-core/dist/tunnel/tcp-tunnel.js +838 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.d.ts +90 -0
- package/vendor/tunnel-core/dist/tunnel/udp-tunnel.js +737 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.d.ts +22 -0
- package/vendor/tunnel-core/dist/tunnel/ws-control.js +124 -0
- package/vendor/tunnel-core/dist/types.d.ts +24 -0
- package/vendor/tunnel-core/dist/types.js +2 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.d.ts +41 -0
- package/vendor/tunnel-core/dist/udp-v1/framing.js +158 -0
- package/vendor/tunnel-core/package.json +34 -0
- package/src/control-plane/MqttControlPlaneClient.js +0 -1196
- package/src/control-plane/MqttControlPlaneTransport.js +0 -150
- package/src/lib/fingerprint.js +0 -115
- package/src/lib/jwt-verifier.js +0 -260
- package/src/lib/logger.js +0 -62
- package/src/mqtt/awaiter-map.js +0 -247
- package/src/mqtt/events/handlers.js +0 -300
- package/src/mqtt/events/index.js +0 -222
- package/src/mqtt/events/schemas.js +0 -58
- package/src/mqtt/ingress.js +0 -182
- package/src/state/assignment.js +0 -333
- package/src/tcp-v1/framing.js +0 -203
- package/src/tunnel/http-tunnel.js +0 -1738
- package/src/tunnel/reconnect.js +0 -182
- package/src/tunnel/tcp-tunnel.js +0 -944
- package/src/tunnel/udp-tunnel.js +0 -813
- package/src/tunnel/ws-control.js +0 -135
- package/src/udp-v1/framing.js +0 -203
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP-WS v2 Protocol Constants
|
|
3
|
+
*
|
|
4
|
+
* These constants define the authoritative values for HTTP-WS v2 protocol
|
|
5
|
+
* implementation. They must match the values used by the relay server.
|
|
6
|
+
*
|
|
7
|
+
* @see relay/src/httpws-constants.js
|
|
8
|
+
*/
|
|
9
|
+
export const HTTPWS_V2_TARGET_CHUNK_BYTES: 65536;
|
|
10
|
+
export const HTTPWS_V2_MAX_CHUNK_BYTES: 262144;
|
|
11
|
+
export const HTTPWS_V2_PROTOCOL_ERROR_CLOSE_CODE: 1002;
|
|
12
|
+
export const HTTPWS_V2_PROTOCOL_ERROR_REASON: "httpws_v2_without_negotiation";
|
|
13
|
+
export const HTTP_BODY_CHUNK: 32;
|
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* HTTP-WS v2 Protocol Constants
|
|
3
|
-
*
|
|
3
|
+
*
|
|
4
4
|
* These constants define the authoritative values for HTTP-WS v2 protocol
|
|
5
5
|
* implementation. They must match the values used by the relay server.
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
7
|
* @see relay/src/httpws-constants.js
|
|
8
8
|
*/
|
|
9
|
-
|
|
10
9
|
// S-3: Protocol constants alignment
|
|
11
|
-
export const HTTPWS_V2_TARGET_CHUNK_BYTES = 65_536;
|
|
12
|
-
export const HTTPWS_V2_MAX_CHUNK_BYTES = 262_144;
|
|
10
|
+
export const HTTPWS_V2_TARGET_CHUNK_BYTES = 65_536; // 64 KiB target chunk size
|
|
11
|
+
export const HTTPWS_V2_MAX_CHUNK_BYTES = 262_144; // 256 KiB hard maximum chunk size
|
|
13
12
|
export const HTTPWS_V2_PROTOCOL_ERROR_CLOSE_CODE = 1002; // WebSocket close code for protocol errors
|
|
14
13
|
export const HTTPWS_V2_PROTOCOL_ERROR_REASON = 'httpws_v2_without_negotiation'; // Close reason string
|
|
15
|
-
export const HTTP_BODY_CHUNK = 0x20;
|
|
16
|
-
|
|
14
|
+
export const HTTP_BODY_CHUNK = 0x20; // Frame type for HTTP body chunks (v2)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
export function reconnectEnabled(env?: NodeJS.ProcessEnv): boolean;
|
|
2
|
+
/**
|
|
3
|
+
* Decide what an established connection's close means.
|
|
4
|
+
* Close code 4000 is the relay's application code: "lease_closed" (the control plane
|
|
5
|
+
* ended the lease) and "lease_reconnected" (another connection took the lease over)
|
|
6
|
+
* must not be fought; anything else (relay restart, network loss, 1006, 1001, 1011,
|
|
7
|
+
* protocol errors) is retried.
|
|
8
|
+
*/
|
|
9
|
+
export function classifyDrop(code: any, reason: any): {
|
|
10
|
+
fatal: boolean;
|
|
11
|
+
reason: string;
|
|
12
|
+
};
|
|
13
|
+
/** HTTP status from a ws handshake error ("Unexpected server response: 403"). */
|
|
14
|
+
export function httpStatusOf(err: any): any;
|
|
15
|
+
/**
|
|
16
|
+
* Decide what a failed reconnect attempt means.
|
|
17
|
+
* 401/403 and token verification failures are counted as authorization failures
|
|
18
|
+
* (the token expired or the lease was closed); a few in a row end the tunnel.
|
|
19
|
+
* 409 means the relay still holds the old connection for the lease; retry.
|
|
20
|
+
* 400 means the request itself is malformed; retrying cannot help.
|
|
21
|
+
*/
|
|
22
|
+
export function classifyFailure(err: any): {
|
|
23
|
+
fatal: boolean;
|
|
24
|
+
auth: boolean;
|
|
25
|
+
reason: any;
|
|
26
|
+
};
|
|
27
|
+
/** Seconds-since-epoch exp claim of a JWT, or null. */
|
|
28
|
+
export function jwtExp(jwt: any): any;
|
|
29
|
+
export const DEFAULT_INITIAL_DELAY_MS: 250;
|
|
30
|
+
export const DEFAULT_MAX_DELAY_MS: 5000;
|
|
31
|
+
export const DEFAULT_MAX_OUTAGE_MS: number;
|
|
32
|
+
export const DEFAULT_MAX_AUTH_FAILURES: 3;
|
|
33
|
+
/**
|
|
34
|
+
* Runs the reconnect loop for one tunnel.
|
|
35
|
+
* connect(): Promise resolving when a new connection is open, rejecting otherwise.
|
|
36
|
+
* onGiveUp(reason): called once if the tunnel cannot be reconnected.
|
|
37
|
+
* onAuthFailure(): optional (Story 10.9). Called on the first authorization failure of a
|
|
38
|
+
* streak; it may fetch a new assignment (for example after the tenant moved to another
|
|
39
|
+
* relay, where the old token's relay no longer matches). If it returns true, the streak
|
|
40
|
+
* is reset and the next attempt uses the new assignment at once.
|
|
41
|
+
*/
|
|
42
|
+
export class Reconnector {
|
|
43
|
+
constructor({ kind, log, connect, onGiveUp, env, initialDelayMs, maxDelayMs, maxOutageMs, maxAuthFailures, onAuthFailure, now, sleep, }: {
|
|
44
|
+
kind: any;
|
|
45
|
+
log: any;
|
|
46
|
+
connect: any;
|
|
47
|
+
onGiveUp: any;
|
|
48
|
+
env?: NodeJS.ProcessEnv;
|
|
49
|
+
initialDelayMs?: number;
|
|
50
|
+
maxDelayMs?: any;
|
|
51
|
+
maxOutageMs?: any;
|
|
52
|
+
maxAuthFailures?: number;
|
|
53
|
+
onAuthFailure?: any;
|
|
54
|
+
now?: () => number;
|
|
55
|
+
sleep?: (ms: any) => Promise<any>;
|
|
56
|
+
});
|
|
57
|
+
/** @type {string} */ kind: string;
|
|
58
|
+
log: any;
|
|
59
|
+
/** @type {() => Promise<unknown>} */ connect: () => Promise<unknown>;
|
|
60
|
+
/** @type {(reason: string) => void} */ onGiveUp: (reason: string) => void;
|
|
61
|
+
/** @type {number} */ initialDelayMs: number;
|
|
62
|
+
/** @type {number} */ maxDelayMs: number;
|
|
63
|
+
/** @type {number} */ maxOutageMs: number;
|
|
64
|
+
/** @type {number} */ maxAuthFailures: number;
|
|
65
|
+
/** @type {null | (() => Promise<boolean>)} */ onAuthFailure: null | (() => Promise<boolean>);
|
|
66
|
+
/** @type {() => number} */ now: () => number;
|
|
67
|
+
/** @type {(ms: number) => Promise<unknown>} */ sleep: (ms: number) => Promise<unknown>;
|
|
68
|
+
running: boolean;
|
|
69
|
+
stopped: boolean;
|
|
70
|
+
reconnects: number;
|
|
71
|
+
stop(): void;
|
|
72
|
+
delayFor(attempt: any): number;
|
|
73
|
+
/** Start reconnecting after a drop. Resolves when connected, given up or stopped. */
|
|
74
|
+
run(dropReason: any): Promise<void>;
|
|
75
|
+
giveUp(reason: any, extra?: {}): void;
|
|
76
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Story 11.2: reconnect for TCP and UDP tunnels.
|
|
2
|
+
//
|
|
3
|
+
// When the relay connection of an established TCP or UDP tunnel drops, the tunnel
|
|
4
|
+
// reconnects to the same relay and lease with the newest assignment token instead
|
|
5
|
+
// of ending the CLI. Everything bound to the old connection (TCP streams and their
|
|
6
|
+
// local sockets, UDP flows and their sockets, partial frames) is discarded first,
|
|
7
|
+
// so traffic from before the drop can never be delivered on the new connection.
|
|
8
|
+
//
|
|
9
|
+
// Settings (environment):
|
|
10
|
+
// ASYX_TUNNEL_RECONNECT=0 disable (the tunnel ends on a drop, as before)
|
|
11
|
+
// ASYX_TUNNEL_RECONNECT_MAX_MS give up after this long without a connection (default 15 min)
|
|
12
|
+
// ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS longest wait between attempts (default 5000)
|
|
13
|
+
export const DEFAULT_INITIAL_DELAY_MS = 250;
|
|
14
|
+
export const DEFAULT_MAX_DELAY_MS = 5000;
|
|
15
|
+
export const DEFAULT_MAX_OUTAGE_MS = 15 * 60 * 1000;
|
|
16
|
+
export const DEFAULT_MAX_AUTH_FAILURES = 3;
|
|
17
|
+
export function reconnectEnabled(env = process.env) {
|
|
18
|
+
return env.ASYX_TUNNEL_RECONNECT !== '0';
|
|
19
|
+
}
|
|
20
|
+
function envInt(env, name, fallback) {
|
|
21
|
+
const v = parseInt(env[name] ?? '', 10);
|
|
22
|
+
return Number.isFinite(v) && v > 0 ? v : fallback;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Decide what an established connection's close means.
|
|
26
|
+
* Close code 4000 is the relay's application code: "lease_closed" (the control plane
|
|
27
|
+
* ended the lease) and "lease_reconnected" (another connection took the lease over)
|
|
28
|
+
* must not be fought; anything else (relay restart, network loss, 1006, 1001, 1011,
|
|
29
|
+
* protocol errors) is retried.
|
|
30
|
+
*/
|
|
31
|
+
export function classifyDrop(code, reason) {
|
|
32
|
+
const r = String(reason || '');
|
|
33
|
+
if (code === 4000 && r === 'lease_closed')
|
|
34
|
+
return { fatal: true, reason: 'lease_closed' };
|
|
35
|
+
if (code === 4000 && r === 'lease_reconnected')
|
|
36
|
+
return { fatal: true, reason: 'replaced_by_another_connection' };
|
|
37
|
+
return { fatal: false, reason: `ws_close_${code}` };
|
|
38
|
+
}
|
|
39
|
+
/** HTTP status from a ws handshake error ("Unexpected server response: 403"). */
|
|
40
|
+
export function httpStatusOf(err) {
|
|
41
|
+
if (!err)
|
|
42
|
+
return null;
|
|
43
|
+
if (Number.isInteger(err.httpStatus))
|
|
44
|
+
return err.httpStatus;
|
|
45
|
+
const m = /Unexpected server response: (\d{3})/.exec(err.message || '');
|
|
46
|
+
return m ? Number(m[1]) : null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Decide what a failed reconnect attempt means.
|
|
50
|
+
* 401/403 and token verification failures are counted as authorization failures
|
|
51
|
+
* (the token expired or the lease was closed); a few in a row end the tunnel.
|
|
52
|
+
* 409 means the relay still holds the old connection for the lease; retry.
|
|
53
|
+
* 400 means the request itself is malformed; retrying cannot help.
|
|
54
|
+
*/
|
|
55
|
+
export function classifyFailure(err) {
|
|
56
|
+
const status = httpStatusOf(err);
|
|
57
|
+
if (status === 400)
|
|
58
|
+
return { fatal: true, auth: false, reason: 'bad_request' };
|
|
59
|
+
if (status === 401 || status === 403)
|
|
60
|
+
return { fatal: false, auth: true, reason: `http_${status}` };
|
|
61
|
+
if (err && err.code === 'UDP_RELAY_UNAVAILABLE' && /JWT verification failed/.test(err.message || '')) {
|
|
62
|
+
// Failing to fetch the JWKS (network) is not a token problem: keep retrying
|
|
63
|
+
const cause = err.cause || {};
|
|
64
|
+
const fetchProblem = /JWKS|fetch|timeout|ECONN|ENOTFOUND|EAI_AGAIN|network/i.test(`${cause.code || ''} ${cause.message || ''}`)
|
|
65
|
+
&& !/expired|signature|claim/i.test(`${cause.code || ''} ${cause.message || ''}`);
|
|
66
|
+
if (fetchProblem)
|
|
67
|
+
return { fatal: false, auth: false, reason: 'jwks_unavailable' };
|
|
68
|
+
return { fatal: false, auth: true, reason: 'token_verification_failed' };
|
|
69
|
+
}
|
|
70
|
+
return { fatal: false, auth: false, reason: status ? `http_${status}` : (err?.code || 'connect_failed') };
|
|
71
|
+
}
|
|
72
|
+
/** Seconds-since-epoch exp claim of a JWT, or null. */
|
|
73
|
+
export function jwtExp(jwt) {
|
|
74
|
+
try {
|
|
75
|
+
const part = String(jwt).split('.')[1];
|
|
76
|
+
const payload = JSON.parse(Buffer.from(part.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
|
|
77
|
+
return typeof payload.exp === 'number' ? payload.exp : null;
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Runs the reconnect loop for one tunnel.
|
|
85
|
+
* connect(): Promise resolving when a new connection is open, rejecting otherwise.
|
|
86
|
+
* onGiveUp(reason): called once if the tunnel cannot be reconnected.
|
|
87
|
+
* onAuthFailure(): optional (Story 10.9). Called on the first authorization failure of a
|
|
88
|
+
* streak; it may fetch a new assignment (for example after the tenant moved to another
|
|
89
|
+
* relay, where the old token's relay no longer matches). If it returns true, the streak
|
|
90
|
+
* is reset and the next attempt uses the new assignment at once.
|
|
91
|
+
*/
|
|
92
|
+
export class Reconnector {
|
|
93
|
+
constructor({ kind, log, connect, onGiveUp, env = process.env, initialDelayMs = DEFAULT_INITIAL_DELAY_MS, maxDelayMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_DELAY_MS', DEFAULT_MAX_DELAY_MS), maxOutageMs = envInt(env, 'ASYX_TUNNEL_RECONNECT_MAX_MS', DEFAULT_MAX_OUTAGE_MS), maxAuthFailures = DEFAULT_MAX_AUTH_FAILURES, onAuthFailure = null, now = () => Date.now(), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), }) {
|
|
94
|
+
// Story 12.1 r3: explicit fields (was Object.assign) so the compiler sees them; same values.
|
|
95
|
+
/** @type {string} */ this.kind = kind;
|
|
96
|
+
this.log = log;
|
|
97
|
+
/** @type {() => Promise<unknown>} */ this.connect = connect;
|
|
98
|
+
/** @type {(reason: string) => void} */ this.onGiveUp = onGiveUp;
|
|
99
|
+
/** @type {number} */ this.initialDelayMs = initialDelayMs;
|
|
100
|
+
/** @type {number} */ this.maxDelayMs = maxDelayMs;
|
|
101
|
+
/** @type {number} */ this.maxOutageMs = maxOutageMs;
|
|
102
|
+
/** @type {number} */ this.maxAuthFailures = maxAuthFailures;
|
|
103
|
+
/** @type {null | (() => Promise<boolean>)} */ this.onAuthFailure = onAuthFailure;
|
|
104
|
+
/** @type {() => number} */ this.now = now;
|
|
105
|
+
/** @type {(ms: number) => Promise<unknown>} */ this.sleep = sleep;
|
|
106
|
+
this.running = false;
|
|
107
|
+
this.stopped = false;
|
|
108
|
+
this.reconnects = 0;
|
|
109
|
+
}
|
|
110
|
+
stop() {
|
|
111
|
+
this.stopped = true;
|
|
112
|
+
}
|
|
113
|
+
delayFor(attempt) {
|
|
114
|
+
return Math.min(this.maxDelayMs, this.initialDelayMs * 2 ** attempt);
|
|
115
|
+
}
|
|
116
|
+
/** Start reconnecting after a drop. Resolves when connected, given up or stopped. */
|
|
117
|
+
async run(dropReason) {
|
|
118
|
+
if (this.running || this.stopped)
|
|
119
|
+
return;
|
|
120
|
+
this.running = true;
|
|
121
|
+
const started = this.now();
|
|
122
|
+
let authFailures = 0;
|
|
123
|
+
let reassigned = false;
|
|
124
|
+
this.log.warn({ kind: this.kind, reason: dropReason }, `${this.kind}.reconnect.start`);
|
|
125
|
+
try {
|
|
126
|
+
for (let attempt = 0;; attempt++) {
|
|
127
|
+
if (!reassigned)
|
|
128
|
+
await this.sleep(this.delayFor(attempt));
|
|
129
|
+
reassigned = false;
|
|
130
|
+
if (this.stopped)
|
|
131
|
+
return;
|
|
132
|
+
const outageMs = this.now() - started;
|
|
133
|
+
if (outageMs > this.maxOutageMs) {
|
|
134
|
+
this.giveUp('outage_limit', { outageMs, attempts: attempt });
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
await this.connect();
|
|
139
|
+
this.reconnects += 1;
|
|
140
|
+
this.log.info({ kind: this.kind, attempts: attempt + 1, outageMs: this.now() - started, reconnects: this.reconnects }, `${this.kind}.reconnect.ok`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
if (this.stopped)
|
|
145
|
+
return;
|
|
146
|
+
const verdict = classifyFailure(err);
|
|
147
|
+
this.log.warn({ kind: this.kind, attempt: attempt + 1, reason: verdict.reason, error: err?.message }, `${this.kind}.reconnect.attempt_failed`);
|
|
148
|
+
if (verdict.fatal) {
|
|
149
|
+
this.giveUp(verdict.reason, { attempts: attempt + 1 });
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
authFailures = verdict.auth ? authFailures + 1 : 0;
|
|
153
|
+
if (authFailures === 1 && this.onAuthFailure) {
|
|
154
|
+
let got = false;
|
|
155
|
+
try {
|
|
156
|
+
got = await this.onAuthFailure();
|
|
157
|
+
}
|
|
158
|
+
catch (e) {
|
|
159
|
+
this.log.warn({ kind: this.kind, error: e?.message }, `${this.kind}.reconnect.reassign_failed`);
|
|
160
|
+
}
|
|
161
|
+
if (got) {
|
|
162
|
+
this.log.info({ kind: this.kind, attempt: attempt + 1 }, `${this.kind}.reconnect.reassigned`);
|
|
163
|
+
authFailures = 0;
|
|
164
|
+
reassigned = true;
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (authFailures >= this.maxAuthFailures) {
|
|
169
|
+
this.giveUp(`${verdict.reason}_repeated`, { attempts: attempt + 1 });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
finally {
|
|
176
|
+
this.running = false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
giveUp(reason, extra = {}) {
|
|
180
|
+
this.log.error({ kind: this.kind, reason, ...extra }, `${this.kind}.reconnect.gave_up`);
|
|
181
|
+
this.onGiveUp(reason);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import type { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders } from 'node:http';
|
|
3
|
+
import type { Writable } from 'node:stream';
|
|
4
|
+
/** One request the relay sent through the tunnel. */
|
|
5
|
+
export interface SinkRequest {
|
|
6
|
+
method: string;
|
|
7
|
+
path: string;
|
|
8
|
+
headers: OutgoingHttpHeaders | IncomingHttpHeaders;
|
|
9
|
+
}
|
|
10
|
+
/** What the tunnel writes the request body to; http.ClientRequest satisfies it. */
|
|
11
|
+
export type SinkRequestHandle = Writable & {
|
|
12
|
+
on(event: 'error', listener: (err: NodeJS.ErrnoException) => void): SinkRequestHandle;
|
|
13
|
+
destroy(error?: Error): SinkRequestHandle;
|
|
14
|
+
};
|
|
15
|
+
/** Where an HTTP tunnel sends the requests it receives. */
|
|
16
|
+
export interface RequestSink {
|
|
17
|
+
request(req: SinkRequest, onResponse: (res: IncomingMessage) => void): SinkRequestHandle;
|
|
18
|
+
}
|
|
19
|
+
/** The only addresses a local-port sink connects to, in order: IPv4 loopback, then IPv6 loopback. */
|
|
20
|
+
export declare const LOOPBACK_ADDRESSES: readonly [{
|
|
21
|
+
readonly address: "127.0.0.1";
|
|
22
|
+
readonly family: 4;
|
|
23
|
+
}, {
|
|
24
|
+
readonly address: "::1";
|
|
25
|
+
readonly family: 6;
|
|
26
|
+
}];
|
|
27
|
+
type LookupCallback = (err: NodeJS.ErrnoException | null, address: string | {
|
|
28
|
+
address: string;
|
|
29
|
+
family: number;
|
|
30
|
+
}[], family?: number) => void;
|
|
31
|
+
/** dns.lookup replacement for the sink: ignores the name and returns loopback only. */
|
|
32
|
+
export declare function loopbackLookup(_hostname: string, options: {
|
|
33
|
+
all?: boolean;
|
|
34
|
+
} | number | LookupCallback, callback?: LookupCallback): void;
|
|
35
|
+
export declare class LocalPortSink implements RequestSink {
|
|
36
|
+
readonly port: number;
|
|
37
|
+
constructor(port: number);
|
|
38
|
+
request({ method, path, headers }: SinkRequest, onResponse: (res: IncomingMessage) => void): http.ClientRequest;
|
|
39
|
+
}
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Story 12.1 c3 (TypeScript in r3): where an HTTP tunnel sends the requests it receives from the relay.
|
|
2
|
+
//
|
|
3
|
+
// A request sink has one method:
|
|
4
|
+
// request({ method, path, headers }, onResponse) -> a writable request object with the
|
|
5
|
+
// http.ClientRequest surface the tunnel uses (write, end, on('error'), destroy), calling
|
|
6
|
+
// onResponse(res) with a readable response that has statusCode, headers and the stream events.
|
|
7
|
+
//
|
|
8
|
+
// LocalPortSink is the first implementation: it forwards to a service listening on localhost:<port>,
|
|
9
|
+
// which is what the CLI has always done. Handler mode (requests answered in-process by the
|
|
10
|
+
// developer's code, deferred to a later story) can implement the same interface without changing
|
|
11
|
+
// the tunnel or the SDK's API.
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
/** The only addresses a local-port sink connects to, in order: IPv4 loopback, then IPv6 loopback. */
|
|
14
|
+
export const LOOPBACK_ADDRESSES = Object.freeze([
|
|
15
|
+
{ address: '127.0.0.1', family: 4 },
|
|
16
|
+
{ address: '::1', family: 6 },
|
|
17
|
+
]);
|
|
18
|
+
/** dns.lookup replacement for the sink: ignores the name and returns loopback only. */
|
|
19
|
+
export function loopbackLookup(_hostname, options, callback) {
|
|
20
|
+
const cb = (typeof options === 'function' ? options : callback);
|
|
21
|
+
const all = typeof options === 'object' && options !== null && options.all;
|
|
22
|
+
if (all)
|
|
23
|
+
cb(null, LOOPBACK_ADDRESSES.map((a) => ({ ...a })));
|
|
24
|
+
else
|
|
25
|
+
cb(null, LOOPBACK_ADDRESSES[0].address, LOOPBACK_ADDRESSES[0].family);
|
|
26
|
+
}
|
|
27
|
+
export class LocalPortSink {
|
|
28
|
+
port;
|
|
29
|
+
constructor(port) {
|
|
30
|
+
this.port = port;
|
|
31
|
+
}
|
|
32
|
+
request({ method, path, headers }, onResponse) {
|
|
33
|
+
// Defect 11.30: 'localhost' resolves to ::1 first on macOS with Node 18, so a service listening only on
|
|
34
|
+
// 127.0.0.1 refused the connection. Try 127.0.0.1, then ::1, within the same request (autoSelectFamily
|
|
35
|
+
// with a loopback-only lookup; Node 18.13+). Never any other address.
|
|
36
|
+
return http.request({ hostname: 'localhost', port: this.port, path, method, headers: headers,
|
|
37
|
+
lookup: loopbackLookup, autoSelectFamily: true }, onResponse);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
export class TcpTunnel {
|
|
2
|
+
constructor({ relayUrl, jwt, deviceId, requestId, localPort, leaseId, log, coordinatorCore, coordinatorIngress, isControlPlaneConnected, waitForControlPlane, getLastMqttError, getForceReconnect, controlPlaneTimeoutMs, getJwt, reassign, exit, }: {
|
|
3
|
+
relayUrl: any;
|
|
4
|
+
jwt: any;
|
|
5
|
+
deviceId: any;
|
|
6
|
+
requestId: any;
|
|
7
|
+
localPort: any;
|
|
8
|
+
leaseId: any;
|
|
9
|
+
log: any;
|
|
10
|
+
coordinatorCore: any;
|
|
11
|
+
coordinatorIngress: any;
|
|
12
|
+
isControlPlaneConnected?: () => boolean;
|
|
13
|
+
waitForControlPlane?: () => Promise<void>;
|
|
14
|
+
getLastMqttError?: () => any;
|
|
15
|
+
getForceReconnect?: () => any;
|
|
16
|
+
controlPlaneTimeoutMs?: number;
|
|
17
|
+
getJwt?: any;
|
|
18
|
+
reassign?: any;
|
|
19
|
+
exit?: (code: number) => void;
|
|
20
|
+
});
|
|
21
|
+
relayUrl: any;
|
|
22
|
+
jwt: any;
|
|
23
|
+
getJwt: any;
|
|
24
|
+
reassign: any;
|
|
25
|
+
exit: (code: number) => void;
|
|
26
|
+
deviceId: any;
|
|
27
|
+
requestId: any;
|
|
28
|
+
localPort: any;
|
|
29
|
+
leaseId: any;
|
|
30
|
+
log: any;
|
|
31
|
+
ws: WebSocket;
|
|
32
|
+
coordinatorCore: any;
|
|
33
|
+
coordinatorIngress: any;
|
|
34
|
+
isControlPlaneConnected: () => boolean;
|
|
35
|
+
waitForControlPlane: () => Promise<void>;
|
|
36
|
+
getLastMqttError: () => any;
|
|
37
|
+
getForceReconnect: () => any;
|
|
38
|
+
controlPlaneTimeoutMs: number;
|
|
39
|
+
heartbeatTimer: any;
|
|
40
|
+
lastActivityMs: number;
|
|
41
|
+
headers: {
|
|
42
|
+
Authorization: string;
|
|
43
|
+
'X-Asyx-DeviceId': any;
|
|
44
|
+
'X-Asyx-RequestId': any;
|
|
45
|
+
};
|
|
46
|
+
closing: boolean;
|
|
47
|
+
everOpened: boolean;
|
|
48
|
+
lastInboundMs: number;
|
|
49
|
+
reconnectEnabled: boolean;
|
|
50
|
+
reconnector: Reconnector;
|
|
51
|
+
relayId: any;
|
|
52
|
+
activeStreams: Map<any, any>;
|
|
53
|
+
nextStreamId: number;
|
|
54
|
+
frameBuffer: Buffer<ArrayBuffer>;
|
|
55
|
+
protocolViolation: boolean;
|
|
56
|
+
idleTimeoutMs: number;
|
|
57
|
+
pingIntervalMs: number;
|
|
58
|
+
pingTimer: NodeJS.Timeout;
|
|
59
|
+
lastPongMs: number;
|
|
60
|
+
tcpKeepalive: boolean;
|
|
61
|
+
tcpKeepaliveInitialDelay: number;
|
|
62
|
+
open(): Promise<void>;
|
|
63
|
+
_attemptConnect(): Promise<any>;
|
|
64
|
+
_onDropped(code: any, reasonStr: any): void;
|
|
65
|
+
handleBinaryFrame(data: any): void;
|
|
66
|
+
routeFrame(frame: any): void;
|
|
67
|
+
handleProtocolViolation(error: any): void;
|
|
68
|
+
handleStreamOpen(frame: any): void;
|
|
69
|
+
handleStreamData(frame: any): void;
|
|
70
|
+
handleStreamClose(frame: any): void;
|
|
71
|
+
handleStreamError(frame: any): void;
|
|
72
|
+
handlePing(frame: any): void;
|
|
73
|
+
handlePong(frame: any): void;
|
|
74
|
+
handleTcpStream(msg: any): void;
|
|
75
|
+
handleTcpData(msg: any): void;
|
|
76
|
+
startPingKeepalive(): void;
|
|
77
|
+
stopPingKeepalive(): void;
|
|
78
|
+
sendPing(): void;
|
|
79
|
+
handleTcpClose(msg: any): void;
|
|
80
|
+
closeStream(streamId: any): void;
|
|
81
|
+
closeAllStreams(): void;
|
|
82
|
+
close(): void;
|
|
83
|
+
getHeartbeatInterval(): number;
|
|
84
|
+
startHeartbeat(): void;
|
|
85
|
+
sendHeartbeat(): void;
|
|
86
|
+
stopHeartbeat(): void;
|
|
87
|
+
}
|
|
88
|
+
import WebSocket from 'ws';
|
|
89
|
+
import { Reconnector } from './reconnect.js';
|