@decionis/agentsafe 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +10 -1
  2. package/dist/Cli.js +16 -7
  3. package/dist/Cli.js.map +1 -1
  4. package/dist/Index.d.ts +5 -1
  5. package/dist/Index.d.ts.map +1 -1
  6. package/dist/Index.js +5 -1
  7. package/dist/Index.js.map +1 -1
  8. package/dist/cli/CliProcess.d.ts +2 -0
  9. package/dist/cli/CliProcess.d.ts.map +1 -1
  10. package/dist/cli/CliProcess.js +9 -1
  11. package/dist/cli/CliProcess.js.map +1 -1
  12. package/dist/cli/Commands.d.ts +1 -1
  13. package/dist/cli/Commands.d.ts.map +1 -1
  14. package/dist/cli/Commands.js +5 -0
  15. package/dist/cli/Commands.js.map +1 -1
  16. package/dist/cli/Credentials.d.ts.map +1 -1
  17. package/dist/cli/Credentials.js +8 -1
  18. package/dist/cli/Credentials.js.map +1 -1
  19. package/dist/cli/Help.d.ts.map +1 -1
  20. package/dist/cli/Help.js +4 -1
  21. package/dist/cli/Help.js.map +1 -1
  22. package/dist/cli/Intercept.d.ts +66 -0
  23. package/dist/cli/Intercept.d.ts.map +1 -0
  24. package/dist/cli/Intercept.js +374 -0
  25. package/dist/cli/Intercept.js.map +1 -0
  26. package/dist/cli/Login.d.ts +7 -2
  27. package/dist/cli/Login.d.ts.map +1 -1
  28. package/dist/cli/Login.js +106 -3
  29. package/dist/cli/Login.js.map +1 -1
  30. package/dist/cli/Status.d.ts.map +1 -1
  31. package/dist/cli/Status.js +18 -1
  32. package/dist/cli/Status.js.map +1 -1
  33. package/dist/cli/TestCommand.d.ts +33 -2
  34. package/dist/cli/TestCommand.d.ts.map +1 -1
  35. package/dist/cli/TestCommand.js +130 -4
  36. package/dist/cli/TestCommand.js.map +1 -1
  37. package/dist/cli/VerifyIntent.d.ts +28 -0
  38. package/dist/cli/VerifyIntent.d.ts.map +1 -0
  39. package/dist/cli/VerifyIntent.js +136 -0
  40. package/dist/cli/VerifyIntent.js.map +1 -0
  41. package/dist/egress/TransparentDial.d.ts +18 -0
  42. package/dist/egress/TransparentDial.d.ts.map +1 -0
  43. package/dist/egress/TransparentDial.js +33 -0
  44. package/dist/egress/TransparentDial.js.map +1 -0
  45. package/dist/gateway/Activation.d.ts +10 -3
  46. package/dist/gateway/Activation.d.ts.map +1 -1
  47. package/dist/gateway/Activation.js +17 -2
  48. package/dist/gateway/Activation.js.map +1 -1
  49. package/dist/gateway/BoundaryTest.d.ts +54 -0
  50. package/dist/gateway/BoundaryTest.d.ts.map +1 -1
  51. package/dist/gateway/BoundaryTest.js +19 -7
  52. package/dist/gateway/BoundaryTest.js.map +1 -1
  53. package/dist/gateway/Gateway.d.ts +39 -0
  54. package/dist/gateway/Gateway.d.ts.map +1 -1
  55. package/dist/gateway/Gateway.js +62 -4
  56. package/dist/gateway/Gateway.js.map +1 -1
  57. package/dist/gateway/GatewayConfig.d.ts +7 -0
  58. package/dist/gateway/GatewayConfig.d.ts.map +1 -1
  59. package/dist/gateway/GatewayConfig.js +12 -7
  60. package/dist/gateway/GatewayConfig.js.map +1 -1
  61. package/dist/gateway/GatewayReport.d.ts +2 -1
  62. package/dist/gateway/GatewayReport.d.ts.map +1 -1
  63. package/dist/gateway/GatewayReport.js +3 -0
  64. package/dist/gateway/GatewayReport.js.map +1 -1
  65. package/dist/gateway/HostedBoundaryTest.d.ts +118 -0
  66. package/dist/gateway/HostedBoundaryTest.d.ts.map +1 -0
  67. package/dist/gateway/HostedBoundaryTest.js +235 -0
  68. package/dist/gateway/HostedBoundaryTest.js.map +1 -0
  69. package/dist/gateway/InstallSurface.d.ts +26 -0
  70. package/dist/gateway/InstallSurface.d.ts.map +1 -0
  71. package/dist/gateway/InstallSurface.js +53 -0
  72. package/dist/gateway/InstallSurface.js.map +1 -0
  73. package/dist/gateway/ShadowLedger.d.ts +74 -0
  74. package/dist/gateway/ShadowLedger.d.ts.map +1 -0
  75. package/dist/gateway/ShadowLedger.js +112 -0
  76. package/dist/gateway/ShadowLedger.js.map +1 -0
  77. package/dist/http/GatewayHttpServer.d.ts +7 -0
  78. package/dist/http/GatewayHttpServer.d.ts.map +1 -1
  79. package/dist/http/GatewayHttpServer.js +8 -0
  80. package/dist/http/GatewayHttpServer.js.map +1 -1
  81. package/dist/http/InterceptGovernor.d.ts +71 -0
  82. package/dist/http/InterceptGovernor.d.ts.map +1 -0
  83. package/dist/http/InterceptGovernor.js +128 -0
  84. package/dist/http/InterceptGovernor.js.map +1 -0
  85. package/dist/http/InterceptServer.d.ts +124 -0
  86. package/dist/http/InterceptServer.d.ts.map +1 -0
  87. package/dist/http/InterceptServer.js +303 -0
  88. package/dist/http/InterceptServer.js.map +1 -0
  89. package/dist/intercept/ClientHello.d.ts +37 -0
  90. package/dist/intercept/ClientHello.d.ts.map +1 -0
  91. package/dist/intercept/ClientHello.js +216 -0
  92. package/dist/intercept/ClientHello.js.map +1 -0
  93. package/dist/intercept/Der.d.ts +59 -0
  94. package/dist/intercept/Der.d.ts.map +1 -0
  95. package/dist/intercept/Der.js +140 -0
  96. package/dist/intercept/Der.js.map +1 -0
  97. package/dist/intercept/Destination.d.ts +35 -0
  98. package/dist/intercept/Destination.d.ts.map +1 -0
  99. package/dist/intercept/Destination.js +66 -0
  100. package/dist/intercept/Destination.js.map +1 -0
  101. package/dist/intercept/InterceptLedger.d.ts +103 -0
  102. package/dist/intercept/InterceptLedger.d.ts.map +1 -0
  103. package/dist/intercept/InterceptLedger.js +101 -0
  104. package/dist/intercept/InterceptLedger.js.map +1 -0
  105. package/dist/intercept/LeafIssuer.d.ts +40 -0
  106. package/dist/intercept/LeafIssuer.d.ts.map +1 -0
  107. package/dist/intercept/LeafIssuer.js +124 -0
  108. package/dist/intercept/LeafIssuer.js.map +1 -0
  109. package/dist/intercept/RequestHead.d.ts +48 -0
  110. package/dist/intercept/RequestHead.d.ts.map +1 -0
  111. package/dist/intercept/RequestHead.js +163 -0
  112. package/dist/intercept/RequestHead.js.map +1 -0
  113. package/dist/verify/VerifyIntentVector.d.ts +25 -0
  114. package/dist/verify/VerifyIntentVector.d.ts.map +1 -0
  115. package/dist/verify/VerifyIntentVector.js +188 -0
  116. package/dist/verify/VerifyIntentVector.js.map +1 -0
  117. package/package.json +2 -2
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The govern phase of transparent interception: for the destinations an
3
+ * operator lists, the interceptor does not splice the connection through but
4
+ * becomes its other end. A TLS connection is terminated with a leaf certificate
5
+ * minted for the server name from the operator's own authority; a plaintext
6
+ * connection is read as it is. Either way the bytes then reach the gateway's
7
+ * listener, which runs the same lifecycle the addressed gateway runs: the
8
+ * request is captured as an intent, the authority decides, and exactly the
9
+ * authorized request is forwarded once to the real destination, or held, or
10
+ * refused. Destinations not listed are the observe phase's business, spliced
11
+ * through and counted, or refused, as the operator chose.
12
+ *
13
+ * TLS is terminated over a stream that replays the bytes already read while
14
+ * the destination was being decided: Node's TLS reads a raw socket through
15
+ * its handle, beneath the JavaScript stream those bytes were read from, so
16
+ * handing it the socket would lose the hello. The adapter is the one seam
17
+ * where the interceptor's own code touches the ciphertext, and it copies.
18
+ */
19
+ import type { Socket } from "node:net";
20
+ import { Duplex } from "node:stream";
21
+ import type { InterceptProtocol } from "../intercept/Destination.js";
22
+ import type { LeafIssuer } from "../intercept/LeafIssuer.js";
23
+ import type { GatewayHttpServer } from "./GatewayHttpServer.js";
24
+ export type UnlistedPolicy = "passthrough" | "refuse";
25
+ export interface GovernorOptions {
26
+ /** The hosts whose connections are governed, lowercase. */
27
+ readonly hosts: ReadonlySet<string>;
28
+ /** What becomes of a destination not listed: spliced through and counted, or refused. */
29
+ readonly unlisted: UnlistedPolicy;
30
+ /** Mints the leaf a governed TLS connection is terminated with; null refuses governed TLS. */
31
+ readonly issuer: LeafIssuer | null;
32
+ /** How long a governed TLS handshake may take. */
33
+ readonly handshakeTimeoutMs: number;
34
+ }
35
+ export interface GovernorDependencies {
36
+ /** The gateway listener for a governed host, created on first use and kept. */
37
+ readonly gatewayFor: (host: string, protocol: InterceptProtocol) => Promise<GatewayHttpServer>;
38
+ }
39
+ export declare class GovernError extends Error {
40
+ readonly code: "GOVERN_TLS_UNAVAILABLE" | "GOVERN_HANDSHAKE_FAILED" | "GOVERN_GATEWAY_UNAVAILABLE";
41
+ readonly detail: string | null;
42
+ constructor(code: "GOVERN_TLS_UNAVAILABLE" | "GOVERN_HANDSHAKE_FAILED" | "GOVERN_GATEWAY_UNAVAILABLE", detail?: string | null);
43
+ }
44
+ export declare const GOVERN_DEFAULTS: {
45
+ readonly unlisted: "passthrough";
46
+ readonly handshakeTimeoutMs: 10000;
47
+ };
48
+ /**
49
+ * A stream over a socket whose first bytes were already read: it delivers
50
+ * those bytes first, then whatever the socket delivers, and writes through.
51
+ */
52
+ export declare function replayed(socket: Socket, head: Buffer): Duplex;
53
+ export declare class InterceptGovernor {
54
+ private readonly options;
55
+ private readonly dependencies;
56
+ constructor(options: GovernorOptions, dependencies: GovernorDependencies);
57
+ get unlisted(): UnlistedPolicy;
58
+ get hosts(): ReadonlySet<string>;
59
+ governs(host: string): boolean;
60
+ /**
61
+ * Takes a governed connection: terminates TLS where TLS was spoken, and
62
+ * hands the plaintext stream to the host's gateway listener. Rejects with a
63
+ * `GovernError` naming what could not be done; the caller refuses the
64
+ * connection by that name, and the connection is closed.
65
+ */
66
+ take(client: Socket, head: Buffer, destination: {
67
+ readonly protocol: InterceptProtocol;
68
+ readonly host: string;
69
+ }): Promise<void>;
70
+ }
71
+ //# sourceMappingURL=InterceptGovernor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InterceptGovernor.d.ts","sourceRoot":"","sources":["../../src/http/InterceptGovernor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAA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AAc,CAEpC;IAED,IAAW,KAAK,IAAI,WAAW,CAAC,MAAM,CAAC,CAEtC;IAEM,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIrC;;;;;OAKG;IACU,IAAI,CACf,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE;QAAE,QAAQ,CAAC,QAAQ,EAAE,iBAAiB,CAAC;QAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAC3E,OAAO,CAAC,IAAI,CAAC;CAyDjB"}
@@ -0,0 +1,128 @@
1
+ import { Duplex } from "node:stream";
2
+ import { createSecureContext, TLSSocket } from "node:tls";
3
+ export class GovernError extends Error {
4
+ code;
5
+ detail;
6
+ constructor(code, detail = null) {
7
+ super(detail === null ? code : `${code}: ${detail}`);
8
+ this.code = code;
9
+ this.detail = detail;
10
+ this.name = "GovernError";
11
+ }
12
+ }
13
+ export const GOVERN_DEFAULTS = {
14
+ unlisted: "passthrough",
15
+ handshakeTimeoutMs: 10_000,
16
+ };
17
+ /**
18
+ * A stream over a socket whose first bytes were already read: it delivers
19
+ * those bytes first, then whatever the socket delivers, and writes through.
20
+ */
21
+ export function replayed(socket, head) {
22
+ const adapter = new Duplex({
23
+ read() {
24
+ socket.resume();
25
+ },
26
+ write(chunk, _encoding, callback) {
27
+ socket.write(chunk, callback);
28
+ },
29
+ final(callback) {
30
+ socket.end(callback);
31
+ },
32
+ destroy(error, callback) {
33
+ socket.destroy();
34
+ callback(error);
35
+ },
36
+ });
37
+ adapter.push(head);
38
+ socket.on("data", (chunk) => {
39
+ if (!adapter.push(chunk))
40
+ socket.pause();
41
+ });
42
+ socket.once("end", () => adapter.push(null));
43
+ socket.once("error", (error) => adapter.destroy(error));
44
+ socket.once("close", () => adapter.destroy());
45
+ return adapter;
46
+ }
47
+ export class InterceptGovernor {
48
+ options;
49
+ dependencies;
50
+ constructor(options, dependencies) {
51
+ this.options = options;
52
+ this.dependencies = dependencies;
53
+ }
54
+ get unlisted() {
55
+ return this.options.unlisted;
56
+ }
57
+ get hosts() {
58
+ return this.options.hosts;
59
+ }
60
+ governs(host) {
61
+ return this.options.hosts.has(host);
62
+ }
63
+ /**
64
+ * Takes a governed connection: terminates TLS where TLS was spoken, and
65
+ * hands the plaintext stream to the host's gateway listener. Rejects with a
66
+ * `GovernError` naming what could not be done; the caller refuses the
67
+ * connection by that name, and the connection is closed.
68
+ */
69
+ async take(client, head, destination) {
70
+ const listener = await this.dependencies
71
+ .gatewayFor(destination.host, destination.protocol)
72
+ .catch((error) => {
73
+ throw new GovernError("GOVERN_GATEWAY_UNAVAILABLE", error instanceof Error ? error.message : "UNKNOWN");
74
+ });
75
+ if (destination.protocol === "HTTP") {
76
+ // A plaintext request is read from the socket itself, the head first;
77
+ // the socket was paused while the destination was decided.
78
+ client.unshift(head);
79
+ listener.accept(client);
80
+ client.resume();
81
+ return;
82
+ }
83
+ if (this.options.issuer === null)
84
+ throw new GovernError("GOVERN_TLS_UNAVAILABLE");
85
+ const leaf = this.options.issuer.leafFor(destination.host);
86
+ const secured = new TLSSocket(replayed(client, head), {
87
+ isServer: true,
88
+ secureContext: createSecureContext({ cert: leaf.chainPem, key: leaf.keyPem }),
89
+ // HTTP/1.1 alone: a client offering h2 as well settles for it, and one
90
+ // offering h2 alone is refused at the handshake rather than misread.
91
+ ALPNProtocols: ["http/1.1"],
92
+ });
93
+ await new Promise((resolve, reject) => {
94
+ // A client that goes away during the handshake closes or ends the
95
+ // stream underneath without an error surfacing here; each is a refusal
96
+ // now, not a wait for the timer. Once the handshake is done, the same
97
+ // events are the connection's own business, and the one error a socket
98
+ // can emit is absorbed by the listener left here for it.
99
+ let pending = true;
100
+ const timer = setTimeout(() => {
101
+ secured.destroy();
102
+ reject(new GovernError("GOVERN_HANDSHAKE_FAILED", "TIMEOUT"));
103
+ }, this.options.handshakeTimeoutMs);
104
+ const settle = (error) => {
105
+ if (!pending)
106
+ return;
107
+ pending = false;
108
+ clearTimeout(timer);
109
+ if (error === null) {
110
+ resolve();
111
+ return;
112
+ }
113
+ secured.destroy();
114
+ reject(error);
115
+ };
116
+ secured.once("secure", () => settle(null));
117
+ secured.once("error", (error) => settle(new GovernError("GOVERN_HANDSHAKE_FAILED", errorCode(error))));
118
+ secured.once("close", () => settle(new GovernError("GOVERN_HANDSHAKE_FAILED", "CLOSED")));
119
+ secured.once("end", () => settle(new GovernError("GOVERN_HANDSHAKE_FAILED", "CLOSED")));
120
+ });
121
+ listener.accept(secured);
122
+ }
123
+ }
124
+ /** OpenSSL's name for a handshake failure, which Node puts on the error as its code. */
125
+ function errorCode(error) {
126
+ return error.code ?? error.message;
127
+ }
128
+ //# sourceMappingURL=InterceptGovernor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InterceptGovernor.js","sourceRoot":"","sources":["../../src/http/InterceptGovernor.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,mBAAmB,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAuB1D,MAAM,OAAO,WAAY,SAAQ,KAAK;IAElB;IAEA;IAHlB,YACkB,IACqE,EACrE,SAAwB,IAAI;QAE5C,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,MAAM,EAAE,CAAC,CAAC;QAJrC,SAAI,GAAJ,IAAI,CACiE;QACrE,WAAM,GAAN,MAAM,CAAsB;QAG5C,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AAED,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,QAAQ,EAAE,aAAa;IACvB,kBAAkB,EAAE,MAAM;CAClB,CAAC;AAEX;;;GAGG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,IAAY;IACnD,MAAM,OAAO,GAAG,IAAI,MAAM,CAAC;QACzB,IAAI;YACF,MAAM,CAAC,MAA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AI,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,WAAW,CAAC,yBAAyB,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;QAC1F,CAAC,CAAC,CAAC;QACH,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC3B,CAAC;CACF;AAED,wFAAwF;AACxF,SAAS,SAAS,CAAC,KAAY;IAC7B,OAAQ,KAA2B,CAAC,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC;AAC5D,CAAC"}
@@ -0,0 +1,124 @@
1
+ import { type Dial } from "../egress/TransparentDial.js";
2
+ import { type InterceptProtocol } from "../intercept/Destination.js";
3
+ import { type InterceptRefusal, type GovernedCountsSource, type InterceptReport } from "../intercept/InterceptLedger.js";
4
+ import { type InterceptGovernor } from "./InterceptGovernor.js";
5
+ /** One listener: the port it binds, and the port the redirected connections were addressed to. */
6
+ export interface InterceptListenerSpec {
7
+ readonly port: number;
8
+ readonly destinationPort: number;
9
+ }
10
+ export interface InterceptorOptions {
11
+ /** The address the listeners bind; loopback, since REDIRECT delivers locally generated packets there. */
12
+ readonly bind: string;
13
+ readonly listeners: readonly InterceptListenerSpec[];
14
+ /** How long a client has to send bytes that name a destination. */
15
+ readonly peekTimeoutMs: number;
16
+ readonly connectTimeoutMs: number;
17
+ /** How long a spliced connection may stay silent in both directions. */
18
+ readonly idleTimeoutMs: number;
19
+ readonly maxConnections: number;
20
+ }
21
+ export declare const INTERCEPT_DEFAULTS: {
22
+ readonly bind: "127.0.0.1";
23
+ readonly httpPort: 15001;
24
+ readonly httpsPort: 15002;
25
+ readonly peekTimeoutMs: 5000;
26
+ readonly connectTimeoutMs: 10000;
27
+ readonly idleTimeoutMs: 300000;
28
+ readonly maxConnections: 10000;
29
+ };
30
+ export interface BoundListener {
31
+ readonly address: string;
32
+ readonly port: number;
33
+ readonly destinationPort: number;
34
+ }
35
+ export type InterceptEvent = {
36
+ readonly event: "INTERCEPT_STARTED";
37
+ readonly at: string;
38
+ readonly listeners: readonly {
39
+ readonly listen: string;
40
+ readonly for_port: number;
41
+ }[];
42
+ } | {
43
+ readonly event: "INTERCEPT_OBSERVED";
44
+ readonly at: string;
45
+ readonly protocol: InterceptProtocol;
46
+ readonly host: string;
47
+ readonly port: number;
48
+ /** Taken by the gateway rather than spliced through. */
49
+ readonly governed: boolean;
50
+ readonly method?: string;
51
+ readonly target?: string;
52
+ readonly alpn?: readonly string[];
53
+ } | {
54
+ readonly event: "INTERCEPT_REFUSED";
55
+ readonly at: string;
56
+ readonly reason: InterceptRefusal;
57
+ readonly protocol: InterceptProtocol | null;
58
+ readonly host?: string;
59
+ readonly port?: number;
60
+ readonly detail?: string;
61
+ } | {
62
+ readonly event: "INTERCEPT_GOVERNING";
63
+ readonly at: string;
64
+ readonly hosts: readonly string[];
65
+ readonly unlisted: "passthrough" | "refuse";
66
+ /** Whether governed TLS is terminated: an operator authority was given. */
67
+ readonly tls: boolean;
68
+ } | InterceptReport | {
69
+ readonly event: "INTERCEPT_STOPPED";
70
+ readonly at: string;
71
+ readonly signal: string;
72
+ };
73
+ export interface InterceptorDependencies {
74
+ readonly emit: (event: InterceptEvent) => void;
75
+ readonly dial?: Dial;
76
+ readonly now?: () => Date;
77
+ /** The govern phase, when an operator listed destinations; null observes everything. */
78
+ readonly governor?: InterceptGovernor | null;
79
+ /** The gateway's account of a governed destination, for the report; none when nothing is governed. */
80
+ readonly governedCounts?: GovernedCountsSource;
81
+ }
82
+ /**
83
+ * When the interceptor prints its report unasked: as the count of connections
84
+ * reaches each of these, and whenever a day has passed since the last report
85
+ * at the moment a connection is counted. The stop always prints one.
86
+ */
87
+ export declare const INTERCEPT_REPORT_MILESTONES: readonly number[];
88
+ export declare const INTERCEPT_REPORT_INTERVAL_MS: number;
89
+ export declare class Interceptor {
90
+ private readonly options;
91
+ private readonly ledger;
92
+ private readonly servers;
93
+ private readonly bound;
94
+ private readonly active;
95
+ private readonly dial;
96
+ private readonly now;
97
+ private readonly emit;
98
+ private readonly governor;
99
+ private readonly governedCounts;
100
+ private lastReportAt;
101
+ constructor(options: InterceptorOptions, dependencies: InterceptorDependencies);
102
+ /** Binds every listener; a port that cannot be bound closes the ones already bound and rejects. */
103
+ listen(): Promise<readonly BoundListener[]>;
104
+ listeners(): readonly BoundListener[];
105
+ report(): InterceptReport;
106
+ /**
107
+ * The report on its own cadence, so a sidecar that runs for weeks is read
108
+ * without being stopped: at each milestone in the count of connections, and
109
+ * once a day has passed since the last report.
110
+ */
111
+ private reportOnCadence;
112
+ /** Stops accepting, drops every connection, and waits for the listeners to close. */
113
+ close(): Promise<void>;
114
+ private accept;
115
+ /** Reads the client's first bytes until they name a destination, or refuse one, or run out of time. */
116
+ private peek;
117
+ private place;
118
+ /** Both directions, with back-pressure, half-close, an idle bound, and the bytes counted once at the end. */
119
+ private splice;
120
+ private refuse;
121
+ /** Whether a destination is one of this interceptor's own listeners: a connection that would loop. */
122
+ private isSelf;
123
+ }
124
+ //# sourceMappingURL=InterceptServer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InterceptServer.d.ts","sourceRoot":"","sources":["../../src/http/InterceptServer.ts"],"names":[],"mappings":"AAmBA,OAAO,EAAmB,KAAK,IAAI,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAGL,KAAK,iBAAiB,EACvB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,oBAAoB,EACzB,KAAK,eAAe,EACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAe,KAAK,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAE7E,kGAAkG;AAClG,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,eAAe,EAAE,MAAM,CAAC;CAClC;AAED,MAAM,WAAW,kBAAkB;IACjC,yGAAyG;IACzG,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ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B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAZ1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyB;IAChD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAuB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAO;IAC5B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAa;IACjC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAkC;IACvD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAA2B;IACpD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAuB;IACtD,OAAO,CAAC,YAAY,CAAS;gBAGV,OAAO,EAAE,kBAAkB,EAC5C,YAAY,EAAE,uBAAuB;IAUvC,mGAAmG;IACtF,MAAM,IAAI,OAAO,CAAC,SAAS,aAAa,EAAE,CAAC;IAsCjD,SAAS,IAAI,SAAS,aAAa,EAAE;IAIrC,MAAM,IAAI,eAAe;IAKhC;;;;OAIG;IACH,OAAO,CAAC,eAAe;IASvB,qFAAqF;IACxE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAenC,OAAO,CAAC,MAAM;IAWd,uGAAuG;IACvG,OAAO,CAAC,IAAI;YAmCE,KAAK;IAoEnB,6GAA6G;IAC7G,OAAO,CAAC,MAAM;IA2Cd,OAAO,CAAC,MAAM;IAsBd,sGAAsG;IACtG,OAAO,CAAC,MAAM;CAIf"}
@@ -0,0 +1,303 @@
1
+ /**
2
+ * The transparent interceptor: the hop a workload's outbound HTTP and TLS
3
+ * connections are redirected into by the network (an iptables REDIRECT in the
4
+ * pod or container, written by `packaging/intercept/Redirect.sh`) without the
5
+ * workload knowing. Each connection arrives with its destination rewritten to
6
+ * this process, so the interceptor reads the destination from the client's
7
+ * own first bytes, the TLS server name or the HTTP host, dials it, and splices
8
+ * the two sockets. A connection whose destination no byte names is refused:
9
+ * the interceptor forwards to what the client asked for, or to nothing.
10
+ *
11
+ * That is the observe phase, and every destination starts in it: nothing is
12
+ * decrypted, nothing is decided and no request is altered; what is kept is
13
+ * where the workload went, in the ledger, so an operator learns what a
14
+ * workload reaches before governing it. For the destinations an operator
15
+ * lists, the governor (`InterceptGovernor`) takes the connection instead:
16
+ * TLS is terminated under the operator's authority and the gateway's
17
+ * lifecycle runs over each request. Same hop, same ledger.
18
+ */
19
+ import { createServer } from "node:net";
20
+ import { transparentDial } from "../egress/TransparentDial.js";
21
+ import { readDestination, } from "../intercept/Destination.js";
22
+ import { InterceptLedger, } from "../intercept/InterceptLedger.js";
23
+ import { GovernError } from "./InterceptGovernor.js";
24
+ export const INTERCEPT_DEFAULTS = {
25
+ bind: "127.0.0.1",
26
+ httpPort: 15_001,
27
+ httpsPort: 15_002,
28
+ peekTimeoutMs: 5_000,
29
+ connectTimeoutMs: 10_000,
30
+ idleTimeoutMs: 300_000,
31
+ maxConnections: 10_000,
32
+ };
33
+ /**
34
+ * When the interceptor prints its report unasked: as the count of connections
35
+ * reaches each of these, and whenever a day has passed since the last report
36
+ * at the moment a connection is counted. The stop always prints one.
37
+ */
38
+ export const INTERCEPT_REPORT_MILESTONES = [
39
+ 10, 100, 1_000, 10_000, 100_000, 1_000_000,
40
+ ];
41
+ export const INTERCEPT_REPORT_INTERVAL_MS = 24 * 60 * 60 * 1_000;
42
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"]);
43
+ export class Interceptor {
44
+ options;
45
+ ledger = new InterceptLedger();
46
+ servers = [];
47
+ bound = [];
48
+ active = new Set();
49
+ dial;
50
+ now;
51
+ emit;
52
+ governor;
53
+ governedCounts;
54
+ lastReportAt;
55
+ constructor(options, dependencies) {
56
+ this.options = options;
57
+ this.emit = dependencies.emit;
58
+ this.dial = dependencies.dial ?? transparentDial;
59
+ this.now = dependencies.now ?? (() => new Date());
60
+ this.governor = dependencies.governor ?? null;
61
+ this.governedCounts = dependencies.governedCounts ?? (() => null);
62
+ this.lastReportAt = this.now().getTime();
63
+ }
64
+ /** Binds every listener; a port that cannot be bound closes the ones already bound and rejects. */
65
+ async listen() {
66
+ try {
67
+ for (const spec of this.options.listeners) {
68
+ // Half-open stays ours to handle: a client that finishes sending keeps
69
+ // reading the answer, and the destination's end is the client's end.
70
+ const server = createServer({ noDelay: true, allowHalfOpen: true }, (socket) => this.accept(socket, spec));
71
+ await new Promise((resolve, reject) => {
72
+ server.once("error", reject);
73
+ server.listen(spec.port, this.options.bind, () => {
74
+ server.removeListener("error", reject);
75
+ resolve();
76
+ });
77
+ });
78
+ const address = server.address();
79
+ this.servers.push(server);
80
+ this.bound.push({
81
+ address: address.address,
82
+ port: address.port,
83
+ destinationPort: spec.destinationPort,
84
+ });
85
+ }
86
+ }
87
+ catch (error) {
88
+ await this.close();
89
+ throw error;
90
+ }
91
+ this.emit({
92
+ event: "INTERCEPT_STARTED",
93
+ at: this.now().toISOString(),
94
+ listeners: this.bound.map((listener) => ({
95
+ listen: `${listener.address}:${listener.port}`,
96
+ for_port: listener.destinationPort,
97
+ })),
98
+ });
99
+ return this.bound;
100
+ }
101
+ listeners() {
102
+ return this.bound;
103
+ }
104
+ report() {
105
+ this.lastReportAt = this.now().getTime();
106
+ return this.ledger.report(new Date(this.lastReportAt).toISOString(), this.governedCounts);
107
+ }
108
+ /**
109
+ * The report on its own cadence, so a sidecar that runs for weeks is read
110
+ * without being stopped: at each milestone in the count of connections, and
111
+ * once a day has passed since the last report.
112
+ */
113
+ reportOnCadence() {
114
+ if (INTERCEPT_REPORT_MILESTONES.includes(this.ledger.connections) ||
115
+ this.now().getTime() - this.lastReportAt >= INTERCEPT_REPORT_INTERVAL_MS) {
116
+ this.emit(this.report());
117
+ }
118
+ }
119
+ /** Stops accepting, drops every connection, and waits for the listeners to close. */
120
+ async close() {
121
+ for (const socket of this.active)
122
+ socket.destroy();
123
+ this.active.clear();
124
+ const closing = this.servers.splice(0);
125
+ this.bound.splice(0);
126
+ await Promise.all(closing.map((server) => new Promise((resolve) => {
127
+ server.close(() => resolve());
128
+ })));
129
+ }
130
+ accept(client, spec) {
131
+ client.on("error", () => undefined);
132
+ if (this.active.size >= this.options.maxConnections) {
133
+ this.refuse(client, "TOO_MANY_CONNECTIONS", null, undefined, undefined, true);
134
+ return;
135
+ }
136
+ this.active.add(client);
137
+ client.once("close", () => this.active.delete(client));
138
+ this.peek(client, spec);
139
+ }
140
+ /** Reads the client's first bytes until they name a destination, or refuse one, or run out of time. */
141
+ peek(client, spec) {
142
+ const chunks = [];
143
+ let length = 0;
144
+ const finish = () => {
145
+ clearTimeout(timer);
146
+ client.removeListener("data", onData);
147
+ client.removeListener("end", onEnd);
148
+ client.removeListener("close", onEnd);
149
+ };
150
+ const timer = setTimeout(() => {
151
+ finish();
152
+ this.refuse(client, "PEEK_TIMEOUT", null, undefined, undefined, true);
153
+ }, this.options.peekTimeoutMs);
154
+ const onEnd = () => {
155
+ finish();
156
+ this.refuse(client, "DESTINATION_UNKNOWN", null, undefined, undefined, true);
157
+ };
158
+ const onData = (chunk) => {
159
+ chunks.push(chunk);
160
+ length += chunk.length;
161
+ const bytes = Buffer.concat(chunks, length);
162
+ const reading = readDestination(bytes, spec.destinationPort);
163
+ if (reading.kind === "NEED_MORE")
164
+ return;
165
+ finish();
166
+ if (reading.kind === "REFUSED") {
167
+ this.refuse(client, reading.reason, reading.protocol, undefined, reading.detail, true);
168
+ return;
169
+ }
170
+ void this.place(client, bytes, reading);
171
+ };
172
+ client.on("data", onData);
173
+ client.once("end", onEnd);
174
+ client.once("close", onEnd);
175
+ }
176
+ async place(client, head, destination) {
177
+ const at = this.now().toISOString();
178
+ const { protocol, host, port } = destination;
179
+ if (this.isSelf(host, port)) {
180
+ this.refuse(client, "HOST_IS_INTERCEPTOR", protocol, { host, port }, undefined, true);
181
+ return;
182
+ }
183
+ const governed = this.governor?.governs(host) ?? false;
184
+ if (!governed && this.governor?.unlisted === "refuse") {
185
+ this.refuse(client, "UNLISTED_DESTINATION", protocol, { host, port }, undefined, true);
186
+ return;
187
+ }
188
+ const key = this.ledger.record(host, port, protocol, destination.method ?? null, at, governed);
189
+ this.emit({
190
+ event: "INTERCEPT_OBSERVED",
191
+ at,
192
+ protocol,
193
+ host,
194
+ port,
195
+ governed,
196
+ ...(destination.method === undefined ? {} : { method: destination.method }),
197
+ ...(destination.target === undefined ? {} : { target: destination.target }),
198
+ ...(destination.alpn === undefined || destination.alpn.length === 0
199
+ ? {}
200
+ : { alpn: destination.alpn }),
201
+ });
202
+ this.reportOnCadence();
203
+ client.pause();
204
+ if (governed && this.governor !== null) {
205
+ // The gateway becomes the connection's other end; nothing is dialled here.
206
+ try {
207
+ await this.governor.take(client, head, destination);
208
+ }
209
+ catch (error) {
210
+ const detail = error instanceof GovernError ? error.message : "UNKNOWN";
211
+ this.refuse(client, "GOVERN_UNAVAILABLE", protocol, { host, port }, detail, false);
212
+ return;
213
+ }
214
+ this.ledger.placed();
215
+ return;
216
+ }
217
+ // A client that has already finished sending while the destination is
218
+ // dialled must still have its end delivered once the splice is up.
219
+ let clientEnded = false;
220
+ const onEnd = () => {
221
+ clientEnded = true;
222
+ };
223
+ client.once("end", onEnd);
224
+ let upstream;
225
+ try {
226
+ upstream = await this.dial(host, port, this.options.connectTimeoutMs);
227
+ }
228
+ catch (error) {
229
+ const code = error.code ?? "UNREACHABLE";
230
+ this.refuse(client, "UPSTREAM_UNREACHABLE", protocol, { host, port }, code, false);
231
+ return;
232
+ }
233
+ client.removeListener("end", onEnd);
234
+ if (client.destroyed) {
235
+ upstream.destroy();
236
+ return;
237
+ }
238
+ this.ledger.placed();
239
+ this.splice(client, upstream, head, key, clientEnded);
240
+ }
241
+ /** Both directions, with back-pressure, half-close, an idle bound, and the bytes counted once at the end. */
242
+ splice(client, upstream, head, key, clientEnded) {
243
+ let toDestination = head.length;
244
+ let fromDestination = 0;
245
+ let closed = false;
246
+ const closeBoth = () => {
247
+ if (closed)
248
+ return;
249
+ closed = true;
250
+ this.ledger.bytes(key, toDestination, fromDestination);
251
+ client.destroy();
252
+ upstream.destroy();
253
+ };
254
+ upstream.on("error", () => undefined);
255
+ upstream.setNoDelay(true);
256
+ upstream.write(head);
257
+ client.setTimeout(this.options.idleTimeoutMs);
258
+ upstream.setTimeout(this.options.idleTimeoutMs);
259
+ client.on("data", (chunk) => {
260
+ toDestination += chunk.length;
261
+ if (!upstream.write(chunk))
262
+ client.pause();
263
+ });
264
+ upstream.on("drain", () => client.resume());
265
+ upstream.on("data", (chunk) => {
266
+ fromDestination += chunk.length;
267
+ if (!client.write(chunk))
268
+ upstream.pause();
269
+ });
270
+ client.on("drain", () => upstream.resume());
271
+ client.on("end", () => upstream.end());
272
+ upstream.on("end", () => client.end());
273
+ for (const socket of [client, upstream]) {
274
+ socket.on("close", closeBoth);
275
+ socket.on("error", closeBoth);
276
+ socket.on("timeout", closeBoth);
277
+ }
278
+ if (clientEnded)
279
+ upstream.end();
280
+ client.resume();
281
+ }
282
+ refuse(client, reason, protocol, destination, detail, counts) {
283
+ const at = this.now().toISOString();
284
+ this.ledger.refuse(reason, at, counts);
285
+ this.emit({
286
+ event: "INTERCEPT_REFUSED",
287
+ at,
288
+ reason,
289
+ protocol,
290
+ ...(destination === undefined ? {} : destination),
291
+ ...(detail === undefined ? {} : { detail }),
292
+ });
293
+ client.destroy();
294
+ this.reportOnCadence();
295
+ }
296
+ /** Whether a destination is one of this interceptor's own listeners: a connection that would loop. */
297
+ isSelf(host, port) {
298
+ if (!LOOPBACK_HOSTS.has(host) && host !== this.options.bind)
299
+ return false;
300
+ return this.bound.some((listener) => listener.port === port);
301
+ }
302
+ }
303
+ //# sourceMappingURL=InterceptServer.js.map