zero-trust-application-channel 0.0.0-stage → 1.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.
Files changed (76) hide show
  1. package/README.md +67 -2
  2. package/dist/audit/index.d.ts +2 -0
  3. package/dist/audit/index.d.ts.map +1 -0
  4. package/dist/audit/interface.d.ts +29 -0
  5. package/dist/audit/interface.d.ts.map +1 -0
  6. package/dist/channel/index.d.ts +3 -0
  7. package/dist/channel/index.d.ts.map +1 -0
  8. package/dist/channel/interface.d.ts +63 -0
  9. package/dist/channel/interface.d.ts.map +1 -0
  10. package/dist/channel/ws-socket-client.d.ts +36 -0
  11. package/dist/channel/ws-socket-client.d.ts.map +1 -0
  12. package/dist/client/index.d.ts +3 -0
  13. package/dist/client/index.d.ts.map +1 -0
  14. package/dist/client/tunnel-client.d.ts +99 -0
  15. package/dist/client/tunnel-client.d.ts.map +1 -0
  16. package/dist/codec/frame-codec.d.ts +26 -0
  17. package/dist/codec/frame-codec.d.ts.map +1 -0
  18. package/dist/codec/index.d.ts +4 -0
  19. package/dist/codec/index.d.ts.map +1 -0
  20. package/dist/codec/types.d.ts +51 -0
  21. package/dist/codec/types.d.ts.map +1 -0
  22. package/dist/connector/index.d.ts +5 -0
  23. package/dist/connector/index.d.ts.map +1 -0
  24. package/dist/connector/reconnect-delay.d.ts +32 -0
  25. package/dist/connector/reconnect-delay.d.ts.map +1 -0
  26. package/dist/connector/tunnel-connector.d.ts +128 -0
  27. package/dist/connector/tunnel-connector.d.ts.map +1 -0
  28. package/dist/demo/hub-harness.d.ts +31 -0
  29. package/dist/demo/hub-harness.d.ts.map +1 -0
  30. package/dist/hub/index.d.ts +3 -0
  31. package/dist/hub/index.d.ts.map +1 -0
  32. package/dist/hub/registry.d.ts +45 -0
  33. package/dist/hub/registry.d.ts.map +1 -0
  34. package/dist/index.d.ts +13 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +1922 -0
  37. package/dist/logger/index.d.ts +2 -0
  38. package/dist/logger/index.d.ts.map +1 -0
  39. package/dist/logger/interface.d.ts +19 -0
  40. package/dist/logger/interface.d.ts.map +1 -0
  41. package/dist/protocol/index.d.ts +2 -0
  42. package/dist/protocol/index.d.ts.map +1 -0
  43. package/dist/protocol/messages.d.ts +226 -0
  44. package/dist/protocol/messages.d.ts.map +1 -0
  45. package/dist/proxy/hub-session-store.d.ts +55 -0
  46. package/dist/proxy/hub-session-store.d.ts.map +1 -0
  47. package/dist/proxy/index.d.ts +8 -0
  48. package/dist/proxy/index.d.ts.map +1 -0
  49. package/dist/proxy/session-gateway.d.ts +85 -0
  50. package/dist/proxy/session-gateway.d.ts.map +1 -0
  51. package/dist/proxy/stream-sink.d.ts +18 -0
  52. package/dist/proxy/stream-sink.d.ts.map +1 -0
  53. package/dist/proxy/tunnel-proxy.d.ts +126 -0
  54. package/dist/proxy/tunnel-proxy.d.ts.map +1 -0
  55. package/dist/result/domain-error.d.ts +50 -0
  56. package/dist/result/domain-error.d.ts.map +1 -0
  57. package/dist/result/index.d.ts +4 -0
  58. package/dist/result/index.d.ts.map +1 -0
  59. package/dist/result/result.d.ts +24 -0
  60. package/dist/result/result.d.ts.map +1 -0
  61. package/dist/session/__test-helpers__/jose-signer.d.ts +13 -0
  62. package/dist/session/__test-helpers__/jose-signer.d.ts.map +1 -0
  63. package/dist/session/__test-helpers__/jose-signer.js +30 -0
  64. package/dist/session/client-session-server.d.ts +23 -0
  65. package/dist/session/client-session-server.d.ts.map +1 -0
  66. package/dist/session/client-session-store.d.ts +59 -0
  67. package/dist/session/client-session-store.d.ts.map +1 -0
  68. package/dist/session/index.d.ts +4 -0
  69. package/dist/session/index.d.ts.map +1 -0
  70. package/dist/token/index.d.ts +2 -0
  71. package/dist/token/index.d.ts.map +1 -0
  72. package/dist/token/interface.d.ts +18 -0
  73. package/dist/token/interface.d.ts.map +1 -0
  74. package/dist/types.d.ts +16 -0
  75. package/dist/types.d.ts.map +1 -0
  76. package/package.json +61 -4
package/dist/index.js ADDED
@@ -0,0 +1,1922 @@
1
+ // src/result/result.ts
2
+ var VOID_SENTINEL = Symbol("result-void");
3
+
4
+ class Result {
5
+ okValue;
6
+ errValue;
7
+ constructor(okValue, errValue) {
8
+ this.okValue = okValue;
9
+ this.errValue = errValue;
10
+ if (okValue === undefined && errValue === undefined) {
11
+ throw new Error("[Result] ok ve err değeri aynı anda boş olamaz");
12
+ }
13
+ if (okValue !== undefined && errValue !== undefined) {
14
+ throw new Error("[Result] ok ve err değeri aynı anda dolu olamaz");
15
+ }
16
+ if (okValue === null || errValue === null) {
17
+ throw new Error("[Result] null değer kabul edilmez");
18
+ }
19
+ }
20
+ static ok(value) {
21
+ return new Result(value, undefined);
22
+ }
23
+ static err(error) {
24
+ return new Result(undefined, error);
25
+ }
26
+ static okVoid() {
27
+ return new Result(VOID_SENTINEL, undefined);
28
+ }
29
+ isOk() {
30
+ return this.errValue === undefined;
31
+ }
32
+ isErr() {
33
+ return this.okValue === undefined;
34
+ }
35
+ unwrap() {
36
+ if (this.errValue !== undefined) {
37
+ throw new Error("[Result] hata sonucu üzerinde unwrap çağrıldı");
38
+ }
39
+ return this.okValue;
40
+ }
41
+ error() {
42
+ if (this.okValue !== undefined) {
43
+ throw new Error("[Result] başarı sonucu üzerinde error çağrıldı");
44
+ }
45
+ return this.errValue;
46
+ }
47
+ unwrapOr(fallback) {
48
+ return this.errValue === undefined ? this.okValue : fallback;
49
+ }
50
+ map(fn) {
51
+ if (this.errValue !== undefined) {
52
+ return new Result(undefined, this.errValue);
53
+ }
54
+ return new Result(fn(this.okValue), undefined);
55
+ }
56
+ andThen(fn) {
57
+ if (this.errValue !== undefined) {
58
+ return new Result(undefined, this.errValue);
59
+ }
60
+ return fn(this.okValue);
61
+ }
62
+ match(onOk, onErr) {
63
+ if (this.errValue !== undefined) {
64
+ return onErr(this.errValue);
65
+ }
66
+ return onOk(this.okValue);
67
+ }
68
+ }
69
+ // src/result/domain-error.ts
70
+ class DomainError extends Error {
71
+ code;
72
+ kind;
73
+ retryable;
74
+ context;
75
+ cause;
76
+ constructor(code, message, options) {
77
+ super(message);
78
+ this.name = new.target.name;
79
+ if (code.trim().length === 0) {
80
+ throw new Error("[DomainError] code boş olamaz");
81
+ }
82
+ if (message.trim().length === 0) {
83
+ throw new Error("[DomainError] message boş olamaz");
84
+ }
85
+ this.code = code;
86
+ this.kind = options.kind;
87
+ this.retryable = options.retryable;
88
+ this.context = options.context ?? {};
89
+ this.cause = options.cause;
90
+ }
91
+ }
92
+
93
+ class ValidationError extends DomainError {
94
+ constructor(code, message, options) {
95
+ super(code, message, {
96
+ kind: "validation",
97
+ retryable: false,
98
+ context: options?.context,
99
+ cause: options?.cause
100
+ });
101
+ }
102
+ }
103
+
104
+ class NotFoundError extends DomainError {
105
+ constructor(code, message, options) {
106
+ super(code, message, {
107
+ kind: "not_found",
108
+ retryable: false,
109
+ context: options?.context,
110
+ cause: options?.cause
111
+ });
112
+ }
113
+ }
114
+
115
+ class UnauthorizedError extends DomainError {
116
+ constructor(code, message, options) {
117
+ super(code, message, {
118
+ kind: "unauthorized",
119
+ retryable: false,
120
+ context: options?.context,
121
+ cause: options?.cause
122
+ });
123
+ }
124
+ }
125
+
126
+ class ForbiddenError extends DomainError {
127
+ constructor(code, message, options) {
128
+ super(code, message, {
129
+ kind: "forbidden",
130
+ retryable: false,
131
+ context: options?.context,
132
+ cause: options?.cause
133
+ });
134
+ }
135
+ }
136
+
137
+ class ConflictError extends DomainError {
138
+ constructor(code, message, options) {
139
+ super(code, message, {
140
+ kind: "conflict",
141
+ retryable: false,
142
+ context: options?.context,
143
+ cause: options?.cause
144
+ });
145
+ }
146
+ }
147
+
148
+ class TransientError extends DomainError {
149
+ constructor(code, message, options) {
150
+ super(code, message, {
151
+ kind: "transient",
152
+ retryable: true,
153
+ context: options?.context,
154
+ cause: options?.cause
155
+ });
156
+ }
157
+ }
158
+
159
+ class FatalError extends DomainError {
160
+ constructor(code, message, options) {
161
+ super(code, message, {
162
+ kind: "fatal",
163
+ retryable: false,
164
+ context: options?.context,
165
+ cause: options?.cause
166
+ });
167
+ }
168
+ }
169
+ // src/codec/types.ts
170
+ var FRAME_HEADER_SIZE = 9;
171
+ var MAX_CHUNK_SIZE = 64 * 1024;
172
+ var MAX_FRAME_PAYLOAD = 1024 * 1024;
173
+ var FLAG_FIN = 1;
174
+ var FLAG_RST = 2;
175
+ var FLAG_WS_OP = 4;
176
+ var WS_OPCODE = {
177
+ Data: 0,
178
+ Text: 1,
179
+ Binary: 2,
180
+ Close: 8,
181
+ Ping: 9,
182
+ Pong: 10
183
+ };
184
+
185
+ // src/codec/frame-codec.ts
186
+ class FrameDecodeError extends ValidationError {
187
+ constructor(reason) {
188
+ super("tunnel.frame-decode", reason);
189
+ }
190
+ }
191
+
192
+ class FrameCodec {
193
+ encode(frame) {
194
+ validateStreamId(frame.streamId);
195
+ validateSeq(frame.seq);
196
+ const wsOp = (frame.flags & FLAG_WS_OP) === FLAG_WS_OP;
197
+ if (wsOp) {
198
+ if (frame.opcode === undefined) {
199
+ throw new ValidationError("tunnel.opcode-required", "WS_OP set iken opcode zorunludur");
200
+ }
201
+ validateOpcode(frame.opcode);
202
+ } else if (frame.opcode !== undefined) {
203
+ throw new ValidationError("tunnel.opcode-forbidden", "opcode yalnızca WS_OP flag'i ile taşınır");
204
+ }
205
+ if (!(frame.flags >= 0 && frame.flags <= 255)) {
206
+ throw new ValidationError("tunnel.bad-flags", "flags 0-255 araliginda olmali");
207
+ }
208
+ const header = Buffer.allocUnsafe(FRAME_HEADER_SIZE);
209
+ header.writeUInt32BE(frame.streamId, 0);
210
+ header.writeUInt32BE(frame.seq, 4);
211
+ header[8] = frame.flags & 15 | (frame.opcode ?? 0) << 4;
212
+ return Buffer.concat([header, Buffer.from(frame.payload)]);
213
+ }
214
+ decode(buffer, maxPayload = MAX_FRAME_PAYLOAD) {
215
+ if (buffer.length < FRAME_HEADER_SIZE) {
216
+ return Result.err(new FrameDecodeError(`frame cok kisa: ${buffer.length} bayt (min ${FRAME_HEADER_SIZE})`));
217
+ }
218
+ const payloadLength = buffer.length - FRAME_HEADER_SIZE;
219
+ if (payloadLength > maxPayload) {
220
+ return Result.err(new FrameDecodeError(`payload cok buyuk: ${payloadLength} bayt (max ${maxPayload})`));
221
+ }
222
+ const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
223
+ const streamId = view.getUint32(0);
224
+ const seq = view.getUint32(4);
225
+ const flags = view.getUint8(8) & 15;
226
+ const wsOp = (flags & FLAG_WS_OP) === FLAG_WS_OP;
227
+ const opcode = wsOp ? view.getUint8(8) >> 4 : undefined;
228
+ const payload = buffer.subarray(FRAME_HEADER_SIZE);
229
+ return Result.ok({
230
+ streamId,
231
+ seq,
232
+ flags,
233
+ ...opcode !== undefined ? { opcode } : {},
234
+ payload: Uint8Array.from(payload)
235
+ });
236
+ }
237
+ }
238
+ function validateStreamId(value) {
239
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
240
+ throw new ValidationError("tunnel.bad-stream-id", "streamId 0..2^32-1 araliginda tamsayi olmali", { context: { streamId: value } });
241
+ }
242
+ }
243
+ function validateSeq(value) {
244
+ if (!Number.isInteger(value) || value < 0 || value > 4294967295) {
245
+ throw new ValidationError("tunnel.bad-seq", "seq 0..2^32-1 araliginda tamsayi olmali", { context: { seq: value } });
246
+ }
247
+ }
248
+ function validateOpcode(value) {
249
+ if (!Number.isInteger(value) || value < 0 || value > 15) {
250
+ throw new ValidationError("tunnel.bad-opcode", "opcode 4 bit ile sinirli (0-15)", { context: { opcode: value } });
251
+ }
252
+ }
253
+ // src/protocol/messages.ts
254
+ import { z } from "zod";
255
+ var TUNNEL_PROTOCOL_VERSION = 2;
256
+ var TUNNEL_PEER_TYPES = [
257
+ "container",
258
+ "field",
259
+ "device"
260
+ ];
261
+ function isPeerConnectionState(value) {
262
+ return value === "idle" || value === "connected" || value === "stale" || value === "error";
263
+ }
264
+ var tunnelOperationalConfigSchema = z.object({
265
+ heartbeatIntervalMs: z.number().int().min(1000).max(300000).optional()
266
+ });
267
+ var DEFAULT_TUNNEL_OPERATIONAL_CONFIG = Object.freeze({
268
+ heartbeatIntervalMs: 15000
269
+ });
270
+ var TUNNEL_MESSAGE_TYPES = [
271
+ "register",
272
+ "register-ack",
273
+ "config-update",
274
+ "heartbeat",
275
+ "open-session",
276
+ "open-session-ack",
277
+ "session-end",
278
+ "stream-open",
279
+ "stream-open-ack",
280
+ "stream-window",
281
+ "stream-close",
282
+ "error"
283
+ ];
284
+ var serviceAnnouncementSchema = z.object({
285
+ id: z.string().min(1).max(128),
286
+ meta: z.object({
287
+ title: z.string().min(1).max(256).optional(),
288
+ icon: z.string().min(1).max(256).optional()
289
+ }).strict().optional()
290
+ }).strict();
291
+ // src/channel/ws-socket-client.ts
292
+ import { WebSocket } from "ws";
293
+ var READY_STATE_MAP = {
294
+ [WebSocket.CONNECTING]: "connecting",
295
+ [WebSocket.OPEN]: "open",
296
+ [WebSocket.CLOSING]: "closing",
297
+ [WebSocket.CLOSED]: "closed"
298
+ };
299
+
300
+ class WsSocketClient {
301
+ raw;
302
+ constructor(raw) {
303
+ this.raw = raw;
304
+ }
305
+ send(data) {
306
+ this.raw.send(data);
307
+ }
308
+ sendBinary(data) {
309
+ this.raw.send(Buffer.from(data));
310
+ }
311
+ ping() {
312
+ this.raw.ping();
313
+ }
314
+ close() {
315
+ this.raw.close();
316
+ }
317
+ onOpen(callback) {
318
+ this.raw.on("open", callback);
319
+ }
320
+ onMessage(callback) {
321
+ this.raw.on("message", (data, isBinary) => {
322
+ if (isBinary)
323
+ return;
324
+ callback(data.toString());
325
+ });
326
+ }
327
+ onBinaryMessage(callback) {
328
+ this.raw.on("message", (data, isBinary) => {
329
+ if (!isBinary)
330
+ return;
331
+ callback(Buffer.from(data));
332
+ });
333
+ }
334
+ onClose(callback) {
335
+ this.raw.on("close", callback);
336
+ }
337
+ onError(callback) {
338
+ this.raw.on("error", callback);
339
+ }
340
+ onPong(callback) {
341
+ this.raw.on("pong", callback);
342
+ }
343
+ onRejected(callback) {
344
+ this.raw.on("unexpected-response", (_request, response) => {
345
+ callback(response.statusCode ?? 0);
346
+ });
347
+ }
348
+ readyState() {
349
+ return READY_STATE_MAP[this.raw.readyState] ?? "closed";
350
+ }
351
+ }
352
+
353
+ class WsSocketClientFactory {
354
+ creator;
355
+ constructor(creator) {
356
+ this.creator = creator ?? ((url, protocols, options) => new WebSocket(url, protocols, options));
357
+ }
358
+ create(url, headers, protocols = []) {
359
+ return new WsSocketClient(this.creator(url, protocols, { headers }));
360
+ }
361
+ }
362
+ // src/connector/tunnel-connector.ts
363
+ var DEFAULT_TUNNEL_EVENT_CODES = Object.freeze({
364
+ connected: "tunnel_connected",
365
+ connectionLost: "tunnel_connection_lost",
366
+ registerRejected: "tunnel_register_rejected",
367
+ configRejected: "tunnel_config_rejected"
368
+ });
369
+
370
+ class TunnelConnector {
371
+ config;
372
+ socketFactory;
373
+ reconnectDelay;
374
+ logger;
375
+ now;
376
+ stateValue = "offline";
377
+ socket;
378
+ generation = 0;
379
+ attempt = 0;
380
+ urlIndex = 0;
381
+ stopped = false;
382
+ heartbeatTimer;
383
+ registerTimer;
384
+ reconnectTimer;
385
+ lastHeartbeatSentAt;
386
+ lastPongAt = 0;
387
+ operational;
388
+ eventCodes;
389
+ messageSubscribers = new Set;
390
+ binarySubscribers = new Set;
391
+ constructor(config, socketFactory, reconnectDelay, logger, now = () => Date.now()) {
392
+ this.config = config;
393
+ this.socketFactory = socketFactory;
394
+ this.reconnectDelay = reconnectDelay;
395
+ this.logger = logger;
396
+ this.now = now;
397
+ if (config.wsUrls.length === 0) {
398
+ throw new ValidationError("tunnel-connector.no-url", "en az bir hub WS URL gerekli");
399
+ }
400
+ if (config.token.trim().length === 0) {
401
+ throw new ValidationError("tunnel-connector.no-token", "service token bos olamaz");
402
+ }
403
+ if (config.peerId.trim().length === 0) {
404
+ throw new ValidationError("tunnel-connector.no-peer-id", "peerId bos olamaz");
405
+ }
406
+ if (config.heartbeatIntervalMs <= 0) {
407
+ throw new ValidationError("tunnel-connector.invalid-interval", "heartbeat araligi pozitif olmali");
408
+ }
409
+ this.operational = {
410
+ heartbeatIntervalMs: config.heartbeatIntervalMs
411
+ };
412
+ this.eventCodes = {
413
+ ...DEFAULT_TUNNEL_EVENT_CODES,
414
+ ...config.eventCodes
415
+ };
416
+ }
417
+ async start() {
418
+ if (this.stateValue !== "offline")
419
+ return;
420
+ this.stopped = false;
421
+ this.connect();
422
+ }
423
+ async stop() {
424
+ this.stopped = true;
425
+ this.clearTimers();
426
+ this.socket?.close();
427
+ this.socket = undefined;
428
+ this.stateValue = "offline";
429
+ }
430
+ state() {
431
+ return this.stateValue;
432
+ }
433
+ connected() {
434
+ return this.stateValue === "connected";
435
+ }
436
+ lastHeartbeatAt() {
437
+ return this.lastHeartbeatSentAt;
438
+ }
439
+ sendControl(message) {
440
+ this.send(message);
441
+ }
442
+ sendBinary(data) {
443
+ if (this.socket?.readyState() === "open") {
444
+ this.socket.sendBinary(data);
445
+ }
446
+ }
447
+ onMessage(subscriber) {
448
+ this.messageSubscribers.add(subscriber);
449
+ return () => this.messageSubscribers.delete(subscriber);
450
+ }
451
+ onBinaryFrame(subscriber) {
452
+ this.binarySubscribers.add(subscriber);
453
+ return () => this.binarySubscribers.delete(subscriber);
454
+ }
455
+ connect() {
456
+ this.clearTimers();
457
+ this.urlIndex = 0;
458
+ this.stateValue = "connecting";
459
+ const first = this.config.wsUrls[0];
460
+ if (first !== undefined) {
461
+ this.tryUrl(first);
462
+ }
463
+ }
464
+ tryUrl(url) {
465
+ if (this.stopped)
466
+ return;
467
+ const gen = ++this.generation;
468
+ const socket = this.socketFactory.create(url, {
469
+ Authorization: `Bearer ${this.config.token}`
470
+ });
471
+ this.socket = socket;
472
+ socket.onOpen(() => {
473
+ if (gen !== this.generation)
474
+ return;
475
+ if (this.stopped)
476
+ return;
477
+ this.lastPongAt = this.now();
478
+ socket.send(this.registerFrame());
479
+ this.registerTimer = setTimeout(() => {
480
+ if (gen !== this.generation)
481
+ return;
482
+ this.log("warn", "app", this.eventCodes.connectionLost, "Hub register ack alinamadi", {
483
+ reason: "register-timeout"
484
+ });
485
+ this.closeAndBackoff();
486
+ }, this.config.registerTimeoutMs);
487
+ });
488
+ socket.onMessage((raw) => {
489
+ if (gen !== this.generation)
490
+ return;
491
+ this.handleMessage(raw);
492
+ });
493
+ socket.onBinaryMessage((data) => {
494
+ if (gen !== this.generation)
495
+ return;
496
+ this.binarySubscribers.forEach((subscriber) => subscriber(data));
497
+ });
498
+ socket.onClose(() => {
499
+ if (gen !== this.generation)
500
+ return;
501
+ if (this.stopped) {
502
+ this.stateValue = "offline";
503
+ return;
504
+ }
505
+ this.enterBackoff("ws-closed");
506
+ });
507
+ socket.onError((error) => {
508
+ if (gen !== this.generation)
509
+ return;
510
+ this.log("warn", "app", this.eventCodes.connectionLost, "Hub WS soket hatasi", {
511
+ error: error.message
512
+ });
513
+ });
514
+ socket.onPong(() => {
515
+ if (gen !== this.generation)
516
+ return;
517
+ this.lastPongAt = this.now();
518
+ });
519
+ socket.onRejected((statusCode) => {
520
+ if (gen !== this.generation)
521
+ return;
522
+ if (statusCode === 401 || statusCode === 403) {
523
+ this.log("warn", "security", this.eventCodes.registerRejected, "Hub baglantisi reddedildi", {
524
+ statusCode,
525
+ url
526
+ });
527
+ }
528
+ this.urlIndex += 1;
529
+ const next = this.config.wsUrls[this.urlIndex];
530
+ if (next !== undefined) {
531
+ this.tryUrl(next);
532
+ } else {
533
+ this.enterBackoff("rejected");
534
+ }
535
+ });
536
+ }
537
+ handleMessage(raw) {
538
+ let msg;
539
+ try {
540
+ msg = JSON.parse(raw);
541
+ } catch {
542
+ return;
543
+ }
544
+ const type = msg.type;
545
+ switch (type) {
546
+ case "register-ack": {
547
+ const ack = msg;
548
+ if (ack.status !== "ok") {
549
+ this.log("warn", "security", this.eventCodes.registerRejected, "Hub register reddetti", {
550
+ status: String(ack.status ?? "unknown")
551
+ });
552
+ this.closeAndBackoff();
553
+ return;
554
+ }
555
+ if (this.registerTimer)
556
+ clearTimeout(this.registerTimer);
557
+ if (ack.config !== undefined) {
558
+ this.applyOperationalConfig(ack.config);
559
+ }
560
+ this.reconnectDelay.reset();
561
+ this.attempt = 0;
562
+ this.stateValue = "registered";
563
+ this.sendHeartbeat();
564
+ this.scheduleHeartbeat();
565
+ this.log("info", "app", this.eventCodes.connected, "Hub baglantisi kuruldu", {
566
+ peerId: this.config.peerId,
567
+ peerType: this.peerType()
568
+ });
569
+ return;
570
+ }
571
+ case "config-update": {
572
+ const update = msg;
573
+ if (update.config !== undefined) {
574
+ this.applyOperationalConfig(update.config);
575
+ }
576
+ return;
577
+ }
578
+ case "error": {
579
+ const err = msg;
580
+ this.log("warn", "app", this.eventCodes.connectionLost, "Hub protokol hatasi", {
581
+ code: String(err.code ?? "unknown"),
582
+ message: String(err.message ?? "")
583
+ });
584
+ return;
585
+ }
586
+ default:
587
+ this.messageSubscribers.forEach((subscriber) => subscriber(msg));
588
+ return;
589
+ }
590
+ }
591
+ sendHeartbeat() {
592
+ const ts = this.now();
593
+ this.lastHeartbeatSentAt = ts;
594
+ this.socket?.ping();
595
+ if (ts - this.lastPongAt >= this.config.livenessTimeoutMs) {
596
+ this.log("warn", "app", this.eventCodes.connectionLost, "Hub baglantisi yari-olu", {
597
+ reason: "liveness-timeout"
598
+ });
599
+ this.closeAndBackoff();
600
+ return;
601
+ }
602
+ const frame = { type: "heartbeat", ts };
603
+ this.send(frame);
604
+ if (this.stateValue === "registered") {
605
+ this.stateValue = "connected";
606
+ }
607
+ }
608
+ applyOperationalConfig(input) {
609
+ const parsed = tunnelOperationalConfigSchema.safeParse(input);
610
+ if (!parsed.success) {
611
+ this.log("warn", "app", this.eventCodes.configRejected, "Gecersiz operational config", {
612
+ reason: "schema"
613
+ });
614
+ return;
615
+ }
616
+ this.operational = { ...this.operational, ...parsed.data };
617
+ if (this.stateValue === "connected" || this.stateValue === "registered") {
618
+ this.scheduleHeartbeat();
619
+ }
620
+ this.log("info", "app", this.eventCodes.connected, "Operational config uygulandi", {
621
+ heartbeatIntervalMs: this.operational.heartbeatIntervalMs
622
+ });
623
+ }
624
+ scheduleHeartbeat() {
625
+ if (this.heartbeatTimer)
626
+ clearInterval(this.heartbeatTimer);
627
+ this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.operational.heartbeatIntervalMs);
628
+ }
629
+ closeAndBackoff() {
630
+ this.generation += 1;
631
+ this.clearTimers();
632
+ this.socket?.close();
633
+ this.enterBackoff("closed-by-client");
634
+ }
635
+ enterBackoff(reason) {
636
+ if (this.stopped)
637
+ return;
638
+ this.clearTimers();
639
+ this.stateValue = "backoff";
640
+ this.attempt += 1;
641
+ const delay = this.reconnectDelay.delayFor(this.attempt);
642
+ this.log("warn", "app", this.eventCodes.connectionLost, "Hub baglantisi koptu", {
643
+ reason,
644
+ attempt: this.attempt,
645
+ reconnectInMs: delay
646
+ });
647
+ this.reconnectTimer = setTimeout(() => this.connect(), delay);
648
+ }
649
+ clearTimers() {
650
+ if (this.heartbeatTimer)
651
+ clearInterval(this.heartbeatTimer);
652
+ if (this.registerTimer)
653
+ clearTimeout(this.registerTimer);
654
+ if (this.reconnectTimer)
655
+ clearTimeout(this.reconnectTimer);
656
+ this.heartbeatTimer = undefined;
657
+ this.registerTimer = undefined;
658
+ this.reconnectTimer = undefined;
659
+ }
660
+ registerFrame() {
661
+ const services = this.config.services;
662
+ const frame = {
663
+ type: "register",
664
+ peerId: this.config.peerId,
665
+ peerType: this.peerType(),
666
+ protocolVersion: TUNNEL_PROTOCOL_VERSION,
667
+ ...services && services.length > 0 ? { services: [...services] } : {}
668
+ };
669
+ return JSON.stringify(frame);
670
+ }
671
+ peerType() {
672
+ return this.config.peerType ?? "container";
673
+ }
674
+ send(frame) {
675
+ if (this.socket?.readyState() === "open") {
676
+ this.socket.send(JSON.stringify(frame));
677
+ }
678
+ }
679
+ log(level, category, eventCode, message, context) {
680
+ if (!this.logger)
681
+ return;
682
+ this.logger.log({ level, category, eventCode, message, context }).catch(() => {});
683
+ }
684
+ }
685
+ // src/connector/reconnect-delay.ts
686
+ class ReconnectDelay {
687
+ baseMs;
688
+ maxMs;
689
+ jitterSpanMs;
690
+ jitter;
691
+ constructor(config) {
692
+ if (!Number.isInteger(config.baseMs) || config.baseMs <= 0) {
693
+ throw new ValidationError("reconnect.invalid-base", "baseMs pozitif tamsayi olmali", { context: { baseMs: config.baseMs } });
694
+ }
695
+ if (!Number.isInteger(config.maxMs) || config.maxMs < config.baseMs) {
696
+ throw new ValidationError("reconnect.invalid-max", "maxMs tabandan kucuk olamaz", { context: { baseMs: config.baseMs, maxMs: config.maxMs } });
697
+ }
698
+ if (!Number.isFinite(config.jitterSpanMs) || config.jitterSpanMs < 0) {
699
+ throw new ValidationError("reconnect.invalid-jitter-span", "jitterSpanMs negatif olamaz", { context: { jitterSpanMs: config.jitterSpanMs } });
700
+ }
701
+ this.baseMs = config.baseMs;
702
+ this.maxMs = config.maxMs;
703
+ this.jitterSpanMs = config.jitterSpanMs;
704
+ this.jitter = config.jitter;
705
+ }
706
+ delayFor(attempt) {
707
+ if (!Number.isInteger(attempt) || attempt < 1) {
708
+ throw new ValidationError("reconnect.invalid-attempt", "attempt 1 tabanli pozitif tamsayi olmali", { context: { attempt } });
709
+ }
710
+ const jittered = this.jitter();
711
+ if (!(jittered >= 0 && jittered < 1)) {
712
+ throw new ValidationError("reconnect.invalid-jitter", "jitter [0, 1) araliginda olmali", { context: { jitter: jittered } });
713
+ }
714
+ const exponential = this.baseMs * 2 ** (attempt - 1);
715
+ return Math.min(this.maxMs, exponential + Math.floor(jittered * this.jitterSpanMs));
716
+ }
717
+ reset() {}
718
+ }
719
+ // src/client/tunnel-client.ts
720
+ var DEFAULT_WINDOW_SIZE = 256 * 1024;
721
+ var DEFAULT_MAX_STREAMS = 16;
722
+ var DEFAULT_CHUNK_SIZE = 64 * 1024;
723
+ var DEFAULT_MAX_REQUEST_BODY = 1024 * 1024;
724
+ var DEFAULT_IDLE_TIMEOUT_MS = 5 * 60 * 1000;
725
+ var DEFAULT_MAX_AGE_MS = 30 * 60 * 1000;
726
+ var DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
727
+ var HOP_BY_HOP_HEADERS = new Set([
728
+ "connection",
729
+ "keep-alive",
730
+ "transfer-encoding",
731
+ "upgrade",
732
+ "content-encoding",
733
+ "content-length"
734
+ ]);
735
+
736
+ class TunnelClient {
737
+ config;
738
+ codec = new FrameCodec;
739
+ socketFactory;
740
+ routeUpstream;
741
+ streams = new Map;
742
+ sweepTimer;
743
+ channel;
744
+ constructor(config) {
745
+ this.config = {
746
+ webServiceUrl: config.webServiceUrl,
747
+ staticUrl: config.staticUrl,
748
+ windowSize: config.windowSize ?? DEFAULT_WINDOW_SIZE,
749
+ maxStreams: config.maxStreams ?? DEFAULT_MAX_STREAMS,
750
+ chunkSize: config.chunkSize ?? DEFAULT_CHUNK_SIZE,
751
+ maxRequestBody: config.maxRequestBody ?? DEFAULT_MAX_REQUEST_BODY,
752
+ idleTimeoutMs: config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
753
+ maxAgeMs: config.maxAgeMs ?? DEFAULT_MAX_AGE_MS,
754
+ sweepIntervalMs: config.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS
755
+ };
756
+ this.socketFactory = config.socketFactory ?? new WsSocketClientFactory;
757
+ this.routeUpstream = config.routeUpstream ?? ((path) => upstreamUrl(path, config.webServiceUrl, config.staticUrl));
758
+ }
759
+ static create(config) {
760
+ return new TunnelClient(config);
761
+ }
762
+ attach(channel) {
763
+ this.channel = channel;
764
+ channel.onMessage((message) => this.handleControl(message));
765
+ channel.onBinaryFrame((data) => this.handleBinaryFrame(data));
766
+ this.sweepTimer = setInterval(() => this.sweep(), this.config.sweepIntervalMs);
767
+ }
768
+ stop() {
769
+ if (this.sweepTimer)
770
+ clearInterval(this.sweepTimer);
771
+ this.sweepTimer = undefined;
772
+ for (const streamId of Array.from(this.streams.keys())) {
773
+ this.closeStream(streamId, "stopped");
774
+ }
775
+ }
776
+ handleControl(message) {
777
+ const msg = message;
778
+ switch (msg.type) {
779
+ case "stream-open":
780
+ this.onStreamOpen(message);
781
+ return;
782
+ case "stream-window": {
783
+ const window = message;
784
+ const state = this.streams.get(window.streamId);
785
+ if (!state || state.closed)
786
+ return;
787
+ state.credit += window.credit;
788
+ state.lastActivityAt = this.now();
789
+ this.drainWaiting(state);
790
+ return;
791
+ }
792
+ case "stream-close": {
793
+ const close = message;
794
+ this.closeStream(close.streamId, close.reason);
795
+ return;
796
+ }
797
+ default:
798
+ return;
799
+ }
800
+ }
801
+ onStreamOpen(msg) {
802
+ const active = Array.from(this.streams.values()).filter((s) => !s.closed);
803
+ if (active.length >= this.config.maxStreams) {
804
+ this.channel?.sendControl({
805
+ type: "stream-open-ack",
806
+ streamId: msg.streamId,
807
+ statusCode: 503
808
+ });
809
+ this.channel?.sendControl({
810
+ type: "stream-close",
811
+ streamId: msg.streamId,
812
+ reason: "max-streams"
813
+ });
814
+ return;
815
+ }
816
+ const now = Date.now();
817
+ const state = {
818
+ streamId: msg.streamId,
819
+ kind: msg.upgrade === "websocket" ? "ws" : "http",
820
+ seq: 0,
821
+ closed: false,
822
+ credit: 0,
823
+ waiting: [],
824
+ controller: new AbortController,
825
+ createdAt: now,
826
+ lastActivityAt: now,
827
+ request: msg,
828
+ awaitingBody: needsBody(msg.method),
829
+ bodyChunks: [],
830
+ bodyBytes: 0
831
+ };
832
+ this.streams.set(msg.streamId, state);
833
+ if (state.kind === "ws") {
834
+ this.openWsBridge(state);
835
+ } else if (!state.awaitingBody) {
836
+ this.fetchStream(state, undefined);
837
+ }
838
+ }
839
+ handleBinaryFrame(data) {
840
+ const result = this.codec.decode(new Uint8Array(data));
841
+ if (result.isErr())
842
+ return;
843
+ const frame = result.unwrap();
844
+ const state = this.streams.get(frame.streamId);
845
+ if (!state || state.closed)
846
+ return;
847
+ state.lastActivityAt = Date.now();
848
+ if ((frame.flags & FLAG_WS_OP) === FLAG_WS_OP) {
849
+ this.onWsDataFrame(state, frame);
850
+ return;
851
+ }
852
+ this.onBodyFrame(state, frame);
853
+ }
854
+ onWsDataFrame(state, frame) {
855
+ const socket = state.upstreamWs;
856
+ if (!socket || socket.readyState() !== "open")
857
+ return;
858
+ if (frame.opcode === WS_OPCODE.Binary) {
859
+ socket.sendBinary(frame.payload);
860
+ } else {
861
+ socket.send(Buffer.from(frame.payload).toString("utf8"));
862
+ }
863
+ }
864
+ onBodyFrame(state, frame) {
865
+ if (!state.awaitingBody)
866
+ return;
867
+ state.bodyBytes += frame.payload.length;
868
+ if (state.bodyBytes > this.config.maxRequestBody) {
869
+ this.sendRst(state);
870
+ this.closeStream(state.streamId, "request-body-too-large");
871
+ return;
872
+ }
873
+ state.bodyChunks.push(Buffer.from(frame.payload));
874
+ if ((frame.flags & FLAG_FIN) === FLAG_FIN) {
875
+ state.awaitingBody = false;
876
+ this.fetchStream(state, Buffer.concat(state.bodyChunks));
877
+ }
878
+ }
879
+ async fetchStream(state, body) {
880
+ const target = this.routeUpstream(state.request.path);
881
+ let response;
882
+ try {
883
+ response = await fetch(`${target}${state.request.path}`, {
884
+ method: state.request.method,
885
+ headers: state.request.headers,
886
+ body,
887
+ signal: state.controller.signal
888
+ });
889
+ } catch (error) {
890
+ if (!state.closed) {
891
+ this.channel?.sendControl({
892
+ type: "stream-open-ack",
893
+ streamId: state.streamId,
894
+ statusCode: 502
895
+ });
896
+ this.closeStream(state.streamId, "fetch-error");
897
+ }
898
+ return;
899
+ }
900
+ if (state.closed)
901
+ return;
902
+ this.channel?.sendControl({
903
+ type: "stream-open-ack",
904
+ streamId: state.streamId,
905
+ statusCode: response.status,
906
+ headers: filterHeaders(response.headers)
907
+ });
908
+ const reader = response.body?.getReader();
909
+ if (!reader) {
910
+ this.sendFin(state);
911
+ return;
912
+ }
913
+ try {
914
+ for (;; ) {
915
+ const { done, value } = await reader.read();
916
+ if (done)
917
+ break;
918
+ if (state.closed)
919
+ return;
920
+ const sent = await this.sendPayload(state, value);
921
+ if (!sent)
922
+ return;
923
+ }
924
+ this.sendFin(state);
925
+ this.closeStream(state.streamId, "done");
926
+ } catch {
927
+ if (!state.closed) {
928
+ this.closeStream(state.streamId, "fetch-error");
929
+ }
930
+ }
931
+ }
932
+ async sendPayload(state, chunk) {
933
+ for (let offset = 0;offset < chunk.length; ) {
934
+ const piece = chunk.subarray(offset, Math.min(offset + this.config.chunkSize, chunk.length));
935
+ offset += piece.length;
936
+ if (state.closed)
937
+ return false;
938
+ try {
939
+ await this.awaitCredit(state, piece.length);
940
+ } catch {
941
+ return false;
942
+ }
943
+ if (state.closed)
944
+ return false;
945
+ state.credit -= piece.length;
946
+ state.lastActivityAt = Date.now();
947
+ this.channel?.sendBinary(this.codec.encode({
948
+ streamId: state.streamId,
949
+ seq: state.seq++,
950
+ flags: 0,
951
+ payload: piece
952
+ }));
953
+ }
954
+ return true;
955
+ }
956
+ sendFin(state) {
957
+ if (state.closed)
958
+ return;
959
+ this.channel?.sendBinary(this.codec.encode({
960
+ streamId: state.streamId,
961
+ seq: state.seq++,
962
+ flags: FLAG_FIN,
963
+ payload: new Uint8Array(0)
964
+ }));
965
+ }
966
+ openWsBridge(state) {
967
+ const base = this.routeUpstream(state.request.path);
968
+ const wsUrl = base.replace(/^http/, "ws") + state.request.path;
969
+ const headers = wsHandshakeHeaders(state.request.headers);
970
+ headers.origin = wsOrigin(wsUrl);
971
+ const socket = this.socketFactory.create(wsUrl, headers, requestedSubprotocols(state.request.headers?.["sec-websocket-protocol"]));
972
+ state.upstreamWs = socket;
973
+ socket.onOpen(() => {
974
+ if (state.closed)
975
+ return;
976
+ this.channel?.sendControl({
977
+ type: "stream-open-ack",
978
+ streamId: state.streamId,
979
+ statusCode: 101
980
+ });
981
+ });
982
+ socket.onMessage((text) => {
983
+ if (state.closed)
984
+ return;
985
+ state.lastActivityAt = Date.now();
986
+ this.channel?.sendBinary(this.codec.encode({
987
+ streamId: state.streamId,
988
+ seq: state.seq++,
989
+ flags: FLAG_WS_OP,
990
+ opcode: WS_OPCODE.Text,
991
+ payload: new TextEncoder().encode(text)
992
+ }));
993
+ });
994
+ socket.onBinaryMessage((data) => {
995
+ if (state.closed)
996
+ return;
997
+ state.lastActivityAt = Date.now();
998
+ this.channel?.sendBinary(this.codec.encode({
999
+ streamId: state.streamId,
1000
+ seq: state.seq++,
1001
+ flags: FLAG_WS_OP,
1002
+ opcode: WS_OPCODE.Binary,
1003
+ payload: new Uint8Array(data)
1004
+ }));
1005
+ });
1006
+ socket.onClose(() => {
1007
+ if (!state.closed)
1008
+ this.closeStream(state.streamId, "ws-closed");
1009
+ });
1010
+ socket.onError(() => {
1011
+ if (!state.closed)
1012
+ this.closeStream(state.streamId, "ws-error");
1013
+ });
1014
+ socket.onRejected((statusCode) => {
1015
+ if (state.closed)
1016
+ return;
1017
+ this.channel?.sendControl({
1018
+ type: "stream-open-ack",
1019
+ streamId: state.streamId,
1020
+ statusCode: statusCode === 0 ? 502 : statusCode
1021
+ });
1022
+ this.closeStream(state.streamId, "ws-rejected");
1023
+ });
1024
+ }
1025
+ async awaitCredit(state, needed) {
1026
+ while (state.credit < needed && !state.closed) {
1027
+ await new Promise((resolve) => {
1028
+ state.waiting.push(resolve);
1029
+ });
1030
+ }
1031
+ if (state.closed)
1032
+ throw new Error("stream-closed");
1033
+ }
1034
+ drainWaiting(state) {
1035
+ const waiters = state.waiting.splice(0, state.waiting.length);
1036
+ waiters.forEach((resolve) => resolve());
1037
+ }
1038
+ sendRst(state) {
1039
+ this.channel?.sendBinary(this.codec.encode({
1040
+ streamId: state.streamId,
1041
+ seq: state.seq++,
1042
+ flags: FLAG_RST,
1043
+ payload: new Uint8Array(0)
1044
+ }));
1045
+ }
1046
+ closeStream(streamId, reason) {
1047
+ const state = this.streams.get(streamId);
1048
+ if (!state || state.closed)
1049
+ return;
1050
+ state.closed = true;
1051
+ state.controller.abort();
1052
+ state.upstreamWs?.close();
1053
+ this.drainWaiting(state);
1054
+ this.streams.delete(streamId);
1055
+ this.channel?.sendControl({
1056
+ type: "stream-close",
1057
+ streamId,
1058
+ reason
1059
+ });
1060
+ }
1061
+ sweep() {
1062
+ const now = Date.now();
1063
+ for (const state of Array.from(this.streams.values())) {
1064
+ if (state.closed)
1065
+ continue;
1066
+ if (now - state.lastActivityAt >= this.config.idleTimeoutMs) {
1067
+ this.closeStream(state.streamId, "idle-timeout");
1068
+ } else if (now - state.createdAt >= this.config.maxAgeMs) {
1069
+ this.closeStream(state.streamId, "max-age");
1070
+ }
1071
+ }
1072
+ }
1073
+ now() {
1074
+ return Date.now();
1075
+ }
1076
+ }
1077
+ function needsBody(method) {
1078
+ return method === "POST" || method === "PUT" || method === "PATCH";
1079
+ }
1080
+ function upstreamUrl(path, webServiceUrl, staticUrl) {
1081
+ return path.startsWith("/api/") || path.startsWith("/ws/") ? webServiceUrl : staticUrl;
1082
+ }
1083
+ function filterHeaders(headers) {
1084
+ const out = {};
1085
+ headers.forEach((value, key) => {
1086
+ if (HOP_BY_HOP_HEADERS.has(key.toLowerCase()))
1087
+ return;
1088
+ out[key] = value;
1089
+ });
1090
+ return out;
1091
+ }
1092
+ function wsOrigin(url) {
1093
+ const parsed = new URL(url);
1094
+ parsed.protocol = parsed.protocol === "wss:" ? "https:" : "http:";
1095
+ return parsed.origin;
1096
+ }
1097
+ function requestedSubprotocols(header) {
1098
+ if (header === undefined)
1099
+ return [];
1100
+ return header.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
1101
+ }
1102
+ var WS_HANDSHAKE_HEADERS = new Set([
1103
+ "sec-websocket-key",
1104
+ "sec-websocket-version",
1105
+ "sec-websocket-extensions",
1106
+ "sec-websocket-protocol",
1107
+ "upgrade",
1108
+ "connection",
1109
+ "origin"
1110
+ ]);
1111
+ function wsHandshakeHeaders(headers) {
1112
+ if (headers === undefined)
1113
+ return {};
1114
+ const out = {};
1115
+ for (const [key, value] of Object.entries(headers)) {
1116
+ const lower = key.toLowerCase();
1117
+ if (HOP_BY_HOP_HEADERS.has(lower) || WS_HANDSHAKE_HEADERS.has(lower))
1118
+ continue;
1119
+ out[lower] = value;
1120
+ }
1121
+ return out;
1122
+ }
1123
+ // src/session/client-session-store.ts
1124
+ var DEFAULT_TTL_SEC = 4 * 60 * 60;
1125
+ var DEFAULT_IDLE_TIMEOUT_SEC = 15 * 60;
1126
+
1127
+ class ClientSessionStore {
1128
+ tokens;
1129
+ sessions = new Map;
1130
+ ttlSec;
1131
+ idleTimeoutSec;
1132
+ tokenTtlSec;
1133
+ now;
1134
+ constructor(tokens, config = {}) {
1135
+ this.tokens = tokens;
1136
+ this.ttlSec = config.ttlSec ?? DEFAULT_TTL_SEC;
1137
+ this.idleTimeoutSec = config.idleTimeoutSec ?? DEFAULT_IDLE_TIMEOUT_SEC;
1138
+ this.tokenTtlSec = this.ttlSec;
1139
+ this.now = config.now ?? (() => Date.now());
1140
+ }
1141
+ async open(sessionId, user) {
1142
+ const ts = this.now();
1143
+ const session = {
1144
+ sessionId,
1145
+ user,
1146
+ createdAt: ts,
1147
+ lastActivityAt: ts
1148
+ };
1149
+ this.sessions.set(sessionId, session);
1150
+ const token = await this.tokens.sign({
1151
+ sessionId,
1152
+ sub: user.id,
1153
+ username: user.username,
1154
+ role: user.role
1155
+ }, this.tokenTtlSec);
1156
+ return { token, expiresInSec: this.tokenTtlSec };
1157
+ }
1158
+ async authenticate(token) {
1159
+ const payload = await this.tokens.verify(token);
1160
+ if (!payload)
1161
+ return;
1162
+ const session = this.sessions.get(payload.sessionId);
1163
+ if (!session)
1164
+ return;
1165
+ session.lastActivityAt = this.now();
1166
+ return session.user;
1167
+ }
1168
+ end(sessionId) {
1169
+ this.sessions.delete(sessionId);
1170
+ }
1171
+ sweep() {
1172
+ const ts = this.now();
1173
+ this.sessions.forEach((session, sessionId) => {
1174
+ const ageMs = (ts - session.createdAt) / 1000;
1175
+ const idleMs = (ts - session.lastActivityAt) / 1000;
1176
+ if (ageMs >= this.ttlSec || idleMs >= this.idleTimeoutSec) {
1177
+ this.sessions.delete(sessionId);
1178
+ }
1179
+ });
1180
+ }
1181
+ activeCount() {
1182
+ return this.sessions.size;
1183
+ }
1184
+ }
1185
+ // src/session/client-session-server.ts
1186
+ class ClientSessionServer {
1187
+ connector;
1188
+ store;
1189
+ logger;
1190
+ unsubscribe;
1191
+ constructor(connector, store, logger) {
1192
+ this.connector = connector;
1193
+ this.store = store;
1194
+ this.logger = logger;
1195
+ }
1196
+ start() {
1197
+ this.unsubscribe = this.connector.onMessage((message) => {
1198
+ const msg = message;
1199
+ if (msg.type === "open-session") {
1200
+ this.onOpenSession(message);
1201
+ } else if (msg.type === "session-end") {
1202
+ this.store.end(message.sessionId);
1203
+ }
1204
+ });
1205
+ }
1206
+ stop() {
1207
+ this.unsubscribe?.();
1208
+ this.unsubscribe = undefined;
1209
+ }
1210
+ async onOpenSession(msg) {
1211
+ try {
1212
+ const { token, expiresInSec } = await this.store.open(msg.sessionId, {
1213
+ id: msg.user.id,
1214
+ username: msg.user.username,
1215
+ role: msg.user.role
1216
+ });
1217
+ this.connector.sendControl({
1218
+ type: "open-session-ack",
1219
+ sessionId: msg.sessionId,
1220
+ token,
1221
+ expiresInSec
1222
+ });
1223
+ } catch (error) {
1224
+ this.logger?.log({
1225
+ level: "error",
1226
+ category: "security",
1227
+ eventCode: "session_open",
1228
+ message: "Oturum JWT uretilemedi",
1229
+ context: { sessionId: msg.sessionId }
1230
+ }).catch(() => {});
1231
+ }
1232
+ }
1233
+ }
1234
+ // src/hub/registry.ts
1235
+ class HubPeerRegistry {
1236
+ records = new Map;
1237
+ register(input) {
1238
+ if (input.peerId.trim().length === 0) {
1239
+ throw new ValidationError("hub-peer-registry.no-peer-id", "peerId bos olamaz");
1240
+ }
1241
+ this.records.set(input.peerId, {
1242
+ peerId: input.peerId,
1243
+ peerType: input.peerType,
1244
+ services: dedupeById(input.services ?? [])
1245
+ });
1246
+ }
1247
+ updateServices(peerId, services) {
1248
+ const existing = this.records.get(peerId);
1249
+ if (!existing)
1250
+ return;
1251
+ this.records.set(peerId, {
1252
+ ...existing,
1253
+ services: dedupeById(services)
1254
+ });
1255
+ }
1256
+ unregister(peerId) {
1257
+ this.records.delete(peerId);
1258
+ }
1259
+ peers() {
1260
+ return [...this.records.values()];
1261
+ }
1262
+ servicesOf(peerId) {
1263
+ return this.records.get(peerId)?.services ?? [];
1264
+ }
1265
+ isConnected(peerId) {
1266
+ return this.records.has(peerId);
1267
+ }
1268
+ }
1269
+ function dedupeById(services) {
1270
+ const byId = new Map;
1271
+ for (const service of services) {
1272
+ byId.set(service.id, service);
1273
+ }
1274
+ return [...byId.values()];
1275
+ }
1276
+ // src/proxy/hub-session-store.ts
1277
+ var DEFAULT_TTL_MS = 4 * 60 * 60 * 1000;
1278
+ var DEFAULT_IDLE_TIMEOUT_MS2 = 15 * 60 * 1000;
1279
+
1280
+ class HubSessionStore {
1281
+ sessions = new Map;
1282
+ ttlMs;
1283
+ idleTimeoutMs;
1284
+ now;
1285
+ constructor(config = {}) {
1286
+ this.ttlMs = config.ttlMs ?? DEFAULT_TTL_MS;
1287
+ this.idleTimeoutMs = config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS2;
1288
+ this.now = config.now ?? (() => Date.now());
1289
+ }
1290
+ register(session) {
1291
+ this.sessions.set(session.sessionId, session);
1292
+ }
1293
+ byToken(token) {
1294
+ for (const session of this.sessions.values()) {
1295
+ if (session.token === token) {
1296
+ session.lastActivityAt = this.now();
1297
+ return session;
1298
+ }
1299
+ }
1300
+ return;
1301
+ }
1302
+ byId(sessionId) {
1303
+ return this.sessions.get(sessionId);
1304
+ }
1305
+ byIdIterable() {
1306
+ return this.sessions.values();
1307
+ }
1308
+ end(sessionId) {
1309
+ this.sessions.delete(sessionId);
1310
+ }
1311
+ countFor(peerId) {
1312
+ let count = 0;
1313
+ for (const session of this.sessions.values()) {
1314
+ if (session.peerId === peerId)
1315
+ count += 1;
1316
+ }
1317
+ return count;
1318
+ }
1319
+ sweep() {
1320
+ const now = this.now();
1321
+ const expired = [];
1322
+ this.sessions.forEach((session, sessionId) => {
1323
+ if (now - session.createdAt >= this.ttlMs || now - session.lastActivityAt >= this.idleTimeoutMs) {
1324
+ this.sessions.delete(sessionId);
1325
+ expired.push(session);
1326
+ }
1327
+ });
1328
+ return expired;
1329
+ }
1330
+ activeCount() {
1331
+ return this.sessions.size;
1332
+ }
1333
+ }
1334
+ // src/proxy/session-gateway.ts
1335
+ import { randomUUID } from "node:crypto";
1336
+ var DEFAULT_ACK_TIMEOUT_MS = 5000;
1337
+ var DEFAULT_MAX_SESSIONS_PER_PEER = 1;
1338
+ var DEFAULT_SWEEP_INTERVAL_MS2 = 60 * 1000;
1339
+ function mapSessionRole(role) {
1340
+ return role;
1341
+ }
1342
+
1343
+ class SessionGateway {
1344
+ channel;
1345
+ sessions;
1346
+ audit;
1347
+ logger;
1348
+ ackTimeoutMs;
1349
+ maxSessionsPerPeer;
1350
+ sweepIntervalMs;
1351
+ now;
1352
+ pendingAcks = new Map;
1353
+ sweepTimer;
1354
+ unsubscribe;
1355
+ constructor(channel, sessions, audit, logger, config = {}) {
1356
+ this.channel = channel;
1357
+ this.sessions = sessions;
1358
+ this.audit = audit;
1359
+ this.logger = logger;
1360
+ this.ackTimeoutMs = config.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
1361
+ this.maxSessionsPerPeer = config.maxSessionsPerPeer ?? DEFAULT_MAX_SESSIONS_PER_PEER;
1362
+ this.sweepIntervalMs = config.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS2;
1363
+ this.now = config.now ?? (() => Date.now());
1364
+ }
1365
+ initialize() {
1366
+ this.unsubscribe = this.channel.onControlMessage((_peerId, message) => {
1367
+ const msg = message;
1368
+ if (msg.type === "open-session-ack") {
1369
+ const ack = message;
1370
+ const resolve = this.pendingAcks.get(ack.sessionId);
1371
+ if (resolve) {
1372
+ this.pendingAcks.delete(ack.sessionId);
1373
+ resolve(ack);
1374
+ }
1375
+ }
1376
+ });
1377
+ this.sweepTimer = setInterval(() => void this.sweep(), this.sweepIntervalMs);
1378
+ }
1379
+ stop() {
1380
+ if (this.sweepTimer)
1381
+ clearInterval(this.sweepTimer);
1382
+ this.sweepTimer = undefined;
1383
+ this.unsubscribe?.();
1384
+ this.unsubscribe = undefined;
1385
+ }
1386
+ sessionByToken(token) {
1387
+ return this.sessions.byToken(token);
1388
+ }
1389
+ sessionForPeer(peerId) {
1390
+ for (const session of this.sessions.byIdIterable()) {
1391
+ if (session.peerId === peerId)
1392
+ return session;
1393
+ }
1394
+ return;
1395
+ }
1396
+ async openSession(input) {
1397
+ const peerRole = mapSessionRole(input.user.role);
1398
+ if (peerRole === undefined) {
1399
+ return Result.err(new ForbiddenError("session.role-denied", "Bu rol ile oturum acilamaz"));
1400
+ }
1401
+ if (this.sessions.countFor(input.peerId) >= this.maxSessionsPerPeer) {
1402
+ const existing = this.sessionForPeer(input.peerId);
1403
+ if (existing) {
1404
+ this.closeSession(existing.sessionId, "replaced");
1405
+ }
1406
+ }
1407
+ if (!this.channel.isConnected(input.peerId)) {
1408
+ return Result.err(new TransientError("session.offline", "Client su anda bagli degil"));
1409
+ }
1410
+ const sessionId = randomUUID();
1411
+ const ackPromise = new Promise((resolve) => {
1412
+ this.pendingAcks.set(sessionId, resolve);
1413
+ });
1414
+ this.channel.sendControl(input.peerId, {
1415
+ type: "open-session",
1416
+ sessionId,
1417
+ user: {
1418
+ id: input.user.id,
1419
+ username: input.user.username,
1420
+ role: peerRole
1421
+ }
1422
+ });
1423
+ const ack = await Promise.race([
1424
+ ackPromise,
1425
+ new Promise((resolve) => setTimeout(() => resolve(undefined), this.ackTimeoutMs))
1426
+ ]);
1427
+ if (ack === undefined) {
1428
+ this.pendingAcks.delete(sessionId);
1429
+ return Result.err(new TransientError("session.ack-timeout", "Client oturum istegine yanit vermedi"));
1430
+ }
1431
+ const session = {
1432
+ sessionId,
1433
+ peerId: input.peerId,
1434
+ token: ack.token,
1435
+ user: input.user,
1436
+ peerRole,
1437
+ createdAt: this.now(),
1438
+ lastActivityAt: this.now(),
1439
+ bytesIn: 0,
1440
+ bytesOut: 0
1441
+ };
1442
+ try {
1443
+ await this.audit.open({
1444
+ hubId: input.hubId,
1445
+ peerId: input.peerId,
1446
+ sessionId,
1447
+ username: input.user.username,
1448
+ callerRole: input.user.role,
1449
+ peerRole,
1450
+ remoteIp: input.remoteIp
1451
+ });
1452
+ } catch (error) {
1453
+ return Result.err(new FatalError("session.audit-failed", "Oturum denetim kaydi yazilamadi — oturum acilmadi"));
1454
+ }
1455
+ this.sessions.register(session);
1456
+ return Result.ok({
1457
+ sessionId,
1458
+ token: ack.token,
1459
+ expiresInSec: ack.expiresInSec,
1460
+ peerRole
1461
+ });
1462
+ }
1463
+ closeSession(sessionId, reason) {
1464
+ const session = this.sessions.byId(sessionId);
1465
+ if (!session)
1466
+ return;
1467
+ this.sessions.end(sessionId);
1468
+ this.channel.sendControl(session.peerId, {
1469
+ type: "session-end",
1470
+ sessionId,
1471
+ reason
1472
+ });
1473
+ this.audit.close({
1474
+ sessionId,
1475
+ endReason: reason,
1476
+ bytesIn: session.bytesIn,
1477
+ bytesOut: session.bytesOut
1478
+ }).catch(() => {
1479
+ this.logger?.log({
1480
+ level: "error",
1481
+ category: "security",
1482
+ eventCode: "session_end",
1483
+ message: "Oturum kapanis audit'i yazilamadi",
1484
+ context: { sessionId }
1485
+ }).catch(() => {});
1486
+ });
1487
+ }
1488
+ sweep() {
1489
+ const expired = this.sessions.sweep();
1490
+ for (const session of expired) {
1491
+ this.channel.sendControl(session.peerId, {
1492
+ type: "session-end",
1493
+ sessionId: session.sessionId,
1494
+ reason: "expired"
1495
+ });
1496
+ this.audit.close({
1497
+ sessionId: session.sessionId,
1498
+ endReason: "expired",
1499
+ bytesIn: session.bytesIn,
1500
+ bytesOut: session.bytesOut
1501
+ }).catch(() => {});
1502
+ }
1503
+ }
1504
+ }
1505
+ // src/proxy/tunnel-proxy.ts
1506
+ var DEFAULT_ALLOWED_PREFIXES = ["/", "/api/", "/ws/", "/assets/", "/favicon"];
1507
+ var DEFAULT_BLOCKED_PREFIXES = [];
1508
+ var DEFAULT_PATH_ALLOWLIST = {
1509
+ allowedPrefixes: DEFAULT_ALLOWED_PREFIXES,
1510
+ blockedPrefixes: DEFAULT_BLOCKED_PREFIXES
1511
+ };
1512
+ var DEFAULT_COOKIE_NAME = "tunnel_session";
1513
+ var DEFAULT_WINDOW_SIZE2 = 256 * 1024;
1514
+ var DEFAULT_MAX_STREAMS2 = 16;
1515
+ var DEFAULT_STREAM_TIMEOUT_MS = 10 * 1000;
1516
+ var DEFAULT_IDLE_TIMEOUT_MS3 = 5 * 60 * 1000;
1517
+ var DEFAULT_MAX_AGE_MS2 = 30 * 60 * 1000;
1518
+ var DEFAULT_SWEEP_INTERVAL_MS3 = 30 * 1000;
1519
+ var HOP_BY_HOP_HEADERS2 = new Set([
1520
+ "connection",
1521
+ "keep-alive",
1522
+ "transfer-encoding",
1523
+ "upgrade",
1524
+ "host",
1525
+ "content-length"
1526
+ ]);
1527
+ function sessionCookieValue(cookieHeader, cookieName = DEFAULT_COOKIE_NAME) {
1528
+ if (!cookieHeader)
1529
+ return;
1530
+ for (const part of cookieHeader.split(";")) {
1531
+ const eq = part.indexOf("=");
1532
+ if (eq === -1)
1533
+ continue;
1534
+ const name = part.slice(0, eq).trim();
1535
+ if (name === cookieName)
1536
+ return part.slice(eq + 1).trim();
1537
+ }
1538
+ return;
1539
+ }
1540
+ function isPathAllowed(path, allowlist = {}) {
1541
+ const clean = path.split("?")[0] ?? path;
1542
+ const blocked = allowlist.blockedPrefixes ?? DEFAULT_BLOCKED_PREFIXES;
1543
+ const allowed = allowlist.allowedPrefixes ?? DEFAULT_ALLOWED_PREFIXES;
1544
+ for (const prefix of blocked) {
1545
+ if (clean === prefix || clean.startsWith(prefix))
1546
+ return false;
1547
+ }
1548
+ for (const prefix of allowed) {
1549
+ if (prefix === "/" ? clean === "/" : clean.startsWith(prefix)) {
1550
+ return true;
1551
+ }
1552
+ }
1553
+ return false;
1554
+ }
1555
+
1556
+ class TunnelProxy {
1557
+ channel;
1558
+ sessions;
1559
+ logger;
1560
+ config;
1561
+ pathAllowlist;
1562
+ codec = new FrameCodec;
1563
+ now;
1564
+ nextStreamId = 1;
1565
+ pendingAcks = new Map;
1566
+ httpStreams = new Map;
1567
+ wsStreams = new Map;
1568
+ sweepTimer;
1569
+ unsubscribeControl;
1570
+ unsubscribeBinary;
1571
+ constructor(channel, sessions, logger, config = {}) {
1572
+ this.channel = channel;
1573
+ this.sessions = sessions;
1574
+ this.logger = logger;
1575
+ this.config = {
1576
+ windowSize: config.windowSize ?? DEFAULT_WINDOW_SIZE2,
1577
+ maxStreams: config.maxStreams ?? DEFAULT_MAX_STREAMS2,
1578
+ streamTimeoutMs: config.streamTimeoutMs ?? DEFAULT_STREAM_TIMEOUT_MS,
1579
+ idleTimeoutMs: config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS3,
1580
+ maxAgeMs: config.maxAgeMs ?? DEFAULT_MAX_AGE_MS2,
1581
+ sweepIntervalMs: config.sweepIntervalMs ?? DEFAULT_SWEEP_INTERVAL_MS3,
1582
+ cookieName: config.cookieName ?? DEFAULT_COOKIE_NAME
1583
+ };
1584
+ this.pathAllowlist = config.pathAllowlist ?? {};
1585
+ this.now = config.now ?? (() => Date.now());
1586
+ }
1587
+ initialize() {
1588
+ this.unsubscribeControl = this.channel.onControlMessage((_peerId, message) => this.onControlMessage(message));
1589
+ this.unsubscribeBinary = this.channel.onBinaryFrame((peerId, data) => this.onBinaryFrame(peerId, data));
1590
+ this.sweepTimer = setInterval(() => this.sweep(), this.config.sweepIntervalMs);
1591
+ }
1592
+ stop() {
1593
+ if (this.sweepTimer)
1594
+ clearInterval(this.sweepTimer);
1595
+ this.sweepTimer = undefined;
1596
+ this.unsubscribeControl?.();
1597
+ this.unsubscribeControl = undefined;
1598
+ this.unsubscribeBinary?.();
1599
+ this.unsubscribeBinary = undefined;
1600
+ for (const state of this.httpStreams.values())
1601
+ this.cleanupHttp(state, "stopped");
1602
+ for (const state of this.wsStreams.values())
1603
+ this.cleanupWs(state, "stopped");
1604
+ }
1605
+ authenticate(cookieHeader, peerId) {
1606
+ const token = sessionCookieValue(cookieHeader, this.config.cookieName);
1607
+ if (!token)
1608
+ return;
1609
+ const session = this.sessions.byToken(token);
1610
+ if (!session || session.peerId !== peerId)
1611
+ return;
1612
+ return session;
1613
+ }
1614
+ async startHttpStream(input) {
1615
+ const streamId = this.assignStreamId();
1616
+ const ackPromise = this.sendStreamOpen(streamId, input.session, {
1617
+ method: input.method,
1618
+ path: input.path,
1619
+ headers: input.headers
1620
+ });
1621
+ if (!ackPromise)
1622
+ return;
1623
+ if (input.requestBody && input.requestBody.length > 0) {
1624
+ this.sendBodyFrames(streamId, input.requestBody, input.session.peerId);
1625
+ }
1626
+ const ack = await this.raceAck(streamId, ackPromise);
1627
+ if (!ack)
1628
+ return;
1629
+ const state = {
1630
+ streamId,
1631
+ session: input.session,
1632
+ raw: input.raw,
1633
+ seq: 0,
1634
+ bytesOut: 0,
1635
+ lastGranted: 0,
1636
+ finished: false,
1637
+ createdAt: this.now(),
1638
+ lastActivityAt: this.now()
1639
+ };
1640
+ input.raw.status(ack.statusCode, ack.headers ?? {});
1641
+ input.raw.onClose(() => {
1642
+ if (!state.finished) {
1643
+ this.closeStream(streamId, "client-abort");
1644
+ this.cleanupHttp(state, "client-abort");
1645
+ }
1646
+ });
1647
+ this.httpStreams.set(streamId, state);
1648
+ this.grantCredit(streamId, this.config.windowSize);
1649
+ }
1650
+ async startWsBridge(input) {
1651
+ const streamId = this.assignStreamId();
1652
+ const ackPromise = this.sendStreamOpen(streamId, input.session, {
1653
+ method: "GET",
1654
+ path: input.path,
1655
+ upgrade: "websocket",
1656
+ ...input.headers !== undefined ? { headers: input.headers } : {}
1657
+ });
1658
+ if (!ackPromise)
1659
+ return;
1660
+ const ack = await this.raceAck(streamId, ackPromise);
1661
+ if (!ack || ack.statusCode !== 101) {
1662
+ this.logger?.log({
1663
+ level: "warn",
1664
+ category: "security",
1665
+ eventCode: "stream_rejected",
1666
+ message: "WS upstream reddedildi",
1667
+ context: { streamId, statusCode: ack?.statusCode ?? 0 }
1668
+ }).catch(() => {});
1669
+ input.browserSocket.close(1013);
1670
+ return;
1671
+ }
1672
+ const state = {
1673
+ streamId,
1674
+ session: input.session,
1675
+ browserSocket: input.browserSocket,
1676
+ seq: 0,
1677
+ createdAt: this.now(),
1678
+ lastActivityAt: this.now()
1679
+ };
1680
+ this.wsStreams.set(streamId, state);
1681
+ return streamId;
1682
+ }
1683
+ closeWs(streamId, reason) {
1684
+ const state = this.wsStreams.get(streamId);
1685
+ if (!state)
1686
+ return;
1687
+ this.closeStream(streamId, reason);
1688
+ this.cleanupWs(state, reason);
1689
+ }
1690
+ sendWsToPeer(streamId, data, isBinary) {
1691
+ const state = this.wsStreams.get(streamId);
1692
+ if (!state)
1693
+ return;
1694
+ state.lastActivityAt = this.now();
1695
+ this.channel.sendBinary(state.session.peerId, this.codec.encode({
1696
+ streamId,
1697
+ seq: state.seq++,
1698
+ flags: FLAG_WS_OP,
1699
+ opcode: isBinary ? WS_OPCODE.Binary : WS_OPCODE.Text,
1700
+ payload: new Uint8Array(data)
1701
+ }));
1702
+ }
1703
+ sendStreamOpen(streamId, session, request) {
1704
+ const total = this.httpStreams.size + this.wsStreams.size;
1705
+ if (total >= this.config.maxStreams)
1706
+ return;
1707
+ const ackPromise = new Promise((resolve) => {
1708
+ this.pendingAcks.set(streamId, resolve);
1709
+ });
1710
+ this.channel.sendControl(session.peerId, {
1711
+ type: "stream-open",
1712
+ streamId,
1713
+ sessionId: session.sessionId,
1714
+ ...request
1715
+ });
1716
+ return ackPromise;
1717
+ }
1718
+ async raceAck(streamId, ackPromise) {
1719
+ const ack = await Promise.race([
1720
+ ackPromise,
1721
+ new Promise((resolve) => setTimeout(() => resolve(undefined), this.config.streamTimeoutMs))
1722
+ ]);
1723
+ if (ack === undefined) {
1724
+ this.pendingAcks.delete(streamId);
1725
+ return;
1726
+ }
1727
+ return ack;
1728
+ }
1729
+ onControlMessage(message) {
1730
+ const msg = message;
1731
+ if (msg.type === "stream-open-ack") {
1732
+ const ack = message;
1733
+ const resolve = this.pendingAcks.get(ack.streamId);
1734
+ if (resolve) {
1735
+ this.pendingAcks.delete(ack.streamId);
1736
+ resolve(ack);
1737
+ }
1738
+ } else if (msg.type === "stream-close") {
1739
+ const close = message;
1740
+ const http = this.httpStreams.get(close.streamId);
1741
+ if (http)
1742
+ this.cleanupHttp(http, close.reason);
1743
+ const ws = this.wsStreams.get(close.streamId);
1744
+ if (ws)
1745
+ this.cleanupWs(ws, close.reason);
1746
+ }
1747
+ }
1748
+ onBinaryFrame(peerId, data) {
1749
+ const result = this.codec.decode(new Uint8Array(data));
1750
+ if (result.isErr())
1751
+ return;
1752
+ const frame = result.unwrap();
1753
+ const http = this.httpStreams.get(frame.streamId);
1754
+ if (http) {
1755
+ this.onHttpFrame(http, frame);
1756
+ return;
1757
+ }
1758
+ const ws = this.wsStreams.get(frame.streamId);
1759
+ if (ws) {
1760
+ this.onWsFrame(ws, frame);
1761
+ }
1762
+ }
1763
+ onHttpFrame(state, frame) {
1764
+ state.lastActivityAt = this.now();
1765
+ if ((frame.flags & FLAG_RST) === FLAG_RST) {
1766
+ state.raw.destroy();
1767
+ this.cleanupHttp(state, "rst");
1768
+ return;
1769
+ }
1770
+ if (frame.payload.length > 0) {
1771
+ state.raw.write(Buffer.from(frame.payload));
1772
+ state.bytesOut += frame.payload.length;
1773
+ state.session.bytesOut += frame.payload.length;
1774
+ if (state.bytesOut - state.lastGranted >= this.config.windowSize / 2) {
1775
+ state.lastGranted = state.bytesOut;
1776
+ this.grantCredit(state.streamId, this.config.windowSize);
1777
+ }
1778
+ }
1779
+ if ((frame.flags & FLAG_FIN) === FLAG_FIN) {
1780
+ state.finished = true;
1781
+ state.raw.end();
1782
+ this.cleanupHttp(state, "done");
1783
+ }
1784
+ }
1785
+ onWsFrame(state, frame) {
1786
+ state.lastActivityAt = this.now();
1787
+ if ((frame.flags & FLAG_RST) === FLAG_RST) {
1788
+ state.browserSocket.close(1011);
1789
+ this.cleanupWs(state, "rst");
1790
+ return;
1791
+ }
1792
+ if ((frame.flags & FLAG_WS_OP) === FLAG_WS_OP) {
1793
+ const binary = frame.opcode === WS_OPCODE.Binary;
1794
+ state.browserSocket.send(Buffer.from(frame.payload), { binary });
1795
+ state.session.bytesIn += frame.payload.length;
1796
+ }
1797
+ }
1798
+ sendBodyFrames(streamId, body, peerId) {
1799
+ for (let offset = 0;offset < body.length; offset += MAX_CHUNK_SIZE) {
1800
+ const chunk = body.subarray(offset, Math.min(offset + MAX_CHUNK_SIZE, body.length));
1801
+ const isLast = offset + chunk.length >= body.length;
1802
+ this.channel.sendBinary(peerId, this.codec.encode({
1803
+ streamId,
1804
+ seq: 0,
1805
+ flags: isLast ? FLAG_FIN : 0,
1806
+ payload: new Uint8Array(chunk)
1807
+ }));
1808
+ }
1809
+ }
1810
+ grantCredit(streamId, credit) {
1811
+ const session = this.httpStreams.get(streamId)?.session;
1812
+ if (!session)
1813
+ return;
1814
+ this.channel.sendControl(session.peerId, {
1815
+ type: "stream-window",
1816
+ streamId,
1817
+ credit
1818
+ });
1819
+ }
1820
+ closeStream(streamId, reason) {
1821
+ const session = this.httpStreams.get(streamId)?.session ?? this.wsStreams.get(streamId)?.session;
1822
+ if (!session)
1823
+ return;
1824
+ this.channel.sendControl(session.peerId, {
1825
+ type: "stream-close",
1826
+ streamId,
1827
+ reason
1828
+ });
1829
+ }
1830
+ cleanupHttp(state, reason) {
1831
+ if (this.httpStreams.get(state.streamId) !== state)
1832
+ return;
1833
+ this.httpStreams.delete(state.streamId);
1834
+ if (!state.finished)
1835
+ state.raw.destroy();
1836
+ if (reason !== "done" && reason !== "stopped") {
1837
+ this.logStreamClose(state.streamId, reason);
1838
+ }
1839
+ }
1840
+ cleanupWs(state, reason) {
1841
+ if (this.wsStreams.get(state.streamId) !== state)
1842
+ return;
1843
+ this.wsStreams.delete(state.streamId);
1844
+ state.browserSocket.close(1000);
1845
+ if (reason !== "stopped") {
1846
+ this.logStreamClose(state.streamId, reason);
1847
+ }
1848
+ }
1849
+ logStreamClose(streamId, reason) {
1850
+ this.logger?.log({
1851
+ level: "info",
1852
+ category: "security",
1853
+ eventCode: "session_end",
1854
+ message: "Tunel akisi kapandi",
1855
+ context: { streamId, reason }
1856
+ }).catch(() => {});
1857
+ }
1858
+ assignStreamId() {
1859
+ const id = this.nextStreamId;
1860
+ this.nextStreamId += 1;
1861
+ return id;
1862
+ }
1863
+ sweep() {
1864
+ const now = this.now();
1865
+ for (const state of Array.from(this.httpStreams.values())) {
1866
+ if (now - state.lastActivityAt >= this.config.idleTimeoutMs || now - state.createdAt >= this.config.maxAgeMs) {
1867
+ state.raw.destroy();
1868
+ this.closeStream(state.streamId, "idle-timeout");
1869
+ this.cleanupHttp(state, "idle-timeout");
1870
+ }
1871
+ }
1872
+ for (const state of Array.from(this.wsStreams.values())) {
1873
+ if (now - state.lastActivityAt >= this.config.idleTimeoutMs || now - state.createdAt >= this.config.maxAgeMs) {
1874
+ state.browserSocket.close(1011);
1875
+ this.closeStream(state.streamId, "idle-timeout");
1876
+ this.cleanupWs(state, "idle-timeout");
1877
+ }
1878
+ }
1879
+ }
1880
+ }
1881
+ export {
1882
+ ClientSessionServer,
1883
+ ClientSessionStore,
1884
+ ConflictError,
1885
+ DEFAULT_PATH_ALLOWLIST,
1886
+ DEFAULT_TUNNEL_OPERATIONAL_CONFIG,
1887
+ DomainError,
1888
+ FLAG_FIN,
1889
+ FLAG_RST,
1890
+ FLAG_WS_OP,
1891
+ FRAME_HEADER_SIZE,
1892
+ FatalError,
1893
+ ForbiddenError,
1894
+ FrameCodec,
1895
+ FrameDecodeError,
1896
+ HubPeerRegistry,
1897
+ HubSessionStore,
1898
+ MAX_CHUNK_SIZE,
1899
+ MAX_FRAME_PAYLOAD,
1900
+ NotFoundError,
1901
+ ReconnectDelay,
1902
+ Result,
1903
+ SessionGateway,
1904
+ TUNNEL_MESSAGE_TYPES,
1905
+ TUNNEL_PEER_TYPES,
1906
+ TUNNEL_PROTOCOL_VERSION,
1907
+ TransientError,
1908
+ TunnelClient,
1909
+ TunnelConnector,
1910
+ TunnelProxy,
1911
+ UnauthorizedError,
1912
+ ValidationError,
1913
+ WS_OPCODE,
1914
+ WsSocketClient,
1915
+ WsSocketClientFactory,
1916
+ isPathAllowed,
1917
+ isPeerConnectionState,
1918
+ mapSessionRole,
1919
+ serviceAnnouncementSchema,
1920
+ sessionCookieValue,
1921
+ tunnelOperationalConfigSchema
1922
+ };