ceulen 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +83 -0
- package/extensions/lib/registry.test.ts +67 -0
- package/extensions/lib/registry.ts +24 -7
- package/extensions/modules/a2a/configPanel.ts +435 -0
- package/extensions/modules/a2a/index.ts +1117 -0
- package/extensions/modules/a2a/lib/activity.ts +173 -0
- package/extensions/modules/a2a/lib/client.ts +1061 -0
- package/extensions/modules/a2a/lib/config.ts +920 -0
- package/extensions/modules/a2a/lib/discovery.ts +158 -0
- package/extensions/modules/a2a/lib/gateway.ts +889 -0
- package/extensions/modules/a2a/lib/mdns.ts +233 -0
- package/extensions/modules/a2a/lib/outcome.ts +48 -0
- package/extensions/modules/a2a/lib/persistence.ts +123 -0
- package/extensions/modules/a2a/lib/protocol.ts +506 -0
- package/extensions/modules/a2a/lib/registry.ts +146 -0
- package/extensions/modules/a2a/lib/retry.ts +86 -0
- package/extensions/modules/a2a/lib/security.ts +394 -0
- package/extensions/modules/a2a/lib/server.ts +1436 -0
- package/extensions/modules/a2a/test/activity.test.ts +138 -0
- package/extensions/modules/a2a/test/bridge.test.ts +101 -0
- package/extensions/modules/a2a/test/broadcast-parse.test.ts +31 -0
- package/extensions/modules/a2a/test/chai.ts +101 -0
- package/extensions/modules/a2a/test/client.test.ts +856 -0
- package/extensions/modules/a2a/test/completion-guard.test.ts +73 -0
- package/extensions/modules/a2a/test/config.test.ts +1396 -0
- package/extensions/modules/a2a/test/configPanel.test.ts +393 -0
- package/extensions/modules/a2a/test/discovery.test.ts +144 -0
- package/extensions/modules/a2a/test/extension.test.ts +135 -0
- package/extensions/modules/a2a/test/gateway.test.ts +1449 -0
- package/extensions/modules/a2a/test/helpers.ts +39 -0
- package/extensions/modules/a2a/test/mdns.test.ts +131 -0
- package/extensions/modules/a2a/test/outcome.test.ts +61 -0
- package/extensions/modules/a2a/test/persistence.test.ts +92 -0
- package/extensions/modules/a2a/test/protocol.test.ts +217 -0
- package/extensions/modules/a2a/test/registry.test.ts +114 -0
- package/extensions/modules/a2a/test/retry.test.ts +136 -0
- package/extensions/modules/a2a/test/security.test.ts +281 -0
- package/extensions/modules/a2a/test/server.test.ts +1966 -0
- package/extensions/modules/a2a/test/tmp.ts +59 -0
- package/extensions/modules/a2a/test/vendor.test.ts +57 -0
- package/extensions/modules/a2a/types/bonjour-service.d.ts +22 -0
- package/extensions/modules/a2a/vendor/VENDORED.md +18 -0
- package/extensions/modules/a2a/vendor/package.json +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/LICENSE +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/index.js +57 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/KeyValue.js +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.d.ts +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/bonjour.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.d.ts +41 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/browser.js +209 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.d.ts +9 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/dns-txt.js +42 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/mdns-server.js +119 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.d.ts +14 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/registry.js +142 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.d.ts +7 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service-types.js +53 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.d.ts +58 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/service.js +130 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/dns-equal.js +13 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.d.ts +1 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/equal-txt.js +17 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.d.ts +4 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-service.js +22 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.d.ts +3 -0
- package/extensions/modules/a2a/vendor/vendored_deps/bonjour-service/dist/lib/utils/filter-txt.js +6 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/classes.js +23 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/index.js +1761 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/opcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/optioncodes.js +59 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/rcodes.js +50 -0
- package/extensions/modules/a2a/vendor/vendored_deps/dns-packet/types.js +103 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/es6.js +73 -0
- package/extensions/modules/a2a/vendor/vendored_deps/fast-deep-equal/index.js +46 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/ip-codec/index.cjs +250 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/multicast-dns/index.js +205 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/LICENSE +21 -0
- package/extensions/modules/a2a/vendor/vendored_deps/thunky/index.js +55 -0
- package/extensions/modules/advisor/index.ts +20 -2
- package/extensions/modules/advisor/lib/watcher.ts +3 -1
- package/extensions/modules/advisor/test/module.test.ts +64 -1
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +2 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/munin/configPanel.ts +5 -2
- package/extensions/modules/munin/test/configPanel.test.ts +27 -2
- package/extensions/modules/router/configPanel.ts +24 -10
- package/extensions/modules/router/lib/client.ts +6 -4
- package/extensions/modules/router/test/unit.test.ts +83 -2
- package/extensions/modules/rules/index.ts +120 -0
- package/extensions/modules/rules/lib/rules.ts +348 -0
- package/extensions/modules/rules/test/lib.test.ts +263 -0
- package/extensions/modules/rules/test/module.test.ts +222 -0
- package/extensions/modules/subagent/index.ts +19 -6
- package/extensions/modules/subagent/lib/routing.ts +11 -6
- package/extensions/modules/subagent/lib/security.ts +12 -1
- package/extensions/modules/subagent/test/routing.test.ts +174 -0
- package/extensions/modules/todo/configPanel.ts +55 -0
- package/extensions/modules/todo/index.ts +511 -0
- package/extensions/modules/todo/lib/render.ts +271 -0
- package/extensions/modules/todo/lib/settings.ts +73 -0
- package/extensions/modules/todo/test/todo.test.ts +528 -0
- package/extensions/modules/usage/index.ts +11 -0
- package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
- package/extensions/modules/web/configPanel.ts +38 -13
- package/extensions/modules/web/lib/settings.ts +11 -2
- package/extensions/modules/web/test/configPanel.test.ts +67 -1
- package/extensions/modules/zai/configPanel.ts +5 -2
- package/extensions/modules/zai/lib/signing.ts +4 -1
- package/extensions/modules/zai/test/configPanel.test.ts +23 -0
- package/extensions/modules/zai/test/signing.test.ts +19 -0
- package/package.json +2 -2
- package/skills/a2a/SKILL.md +63 -0
|
@@ -0,0 +1,1449 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gateway peer discovery — merge, self-filter, overlay routing.
|
|
3
|
+
*
|
|
4
|
+
* Directory shape (a2a-switchboard GET /.well-known/agent.json, authed):
|
|
5
|
+
* { peers: [{ name, url: "/peer/<name>/", healthy, capabilities, skills }] }
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { assert } from "./chai.js";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import * as path from "node:path";
|
|
11
|
+
|
|
12
|
+
import { DEFAULTS } from "./helpers";
|
|
13
|
+
import { makeTempDir } from "./tmp";
|
|
14
|
+
import { GatewayUpstream, backoffDelayMs, isSelfEntry, mergeGatewayPeers } from "../lib/gateway";
|
|
15
|
+
import { resolvePeer, setGatewayPeers, getGatewayPeers, updateGatewayPeers, type Peer } from "../lib/config";
|
|
16
|
+
import { a2aCall, metrics } from "../lib/client";
|
|
17
|
+
import { describe, it, before, after, beforeEach, afterEach } from "node:test";
|
|
18
|
+
|
|
19
|
+
const GW = "http://127.0.0.1:9920";
|
|
20
|
+
const TOKEN = "gw-secret-token";
|
|
21
|
+
|
|
22
|
+
function merge(
|
|
23
|
+
entries: unknown[],
|
|
24
|
+
self: { name: string; url: string; autoName?: string } = { name: "pi-s2-9910", url: "http://127.0.0.1:9910" },
|
|
25
|
+
key = "k1",
|
|
26
|
+
) {
|
|
27
|
+
return mergeGatewayPeers({
|
|
28
|
+
gatewayUrl: GW,
|
|
29
|
+
token: TOKEN,
|
|
30
|
+
selfName: self.name,
|
|
31
|
+
selfUrl: self.url,
|
|
32
|
+
selfAutoName: self.autoName,
|
|
33
|
+
entries,
|
|
34
|
+
timeoutMs: 120_000,
|
|
35
|
+
key,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function makeResp(body: any, status: number, headers?: Headers): any {
|
|
40
|
+
return {
|
|
41
|
+
ok: status >= 200 && status < 300,
|
|
42
|
+
status,
|
|
43
|
+
headers: headers ?? new Headers(),
|
|
44
|
+
json: async () => body,
|
|
45
|
+
text: async () => JSON.stringify(body),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
describe("gateway peer discovery", () => {
|
|
50
|
+
describe("mergeGatewayPeers", () => {
|
|
51
|
+
it("merges peers as gw/<key>/<name> with proxy URL and gateway bearer auth", () => {
|
|
52
|
+
const out = merge([
|
|
53
|
+
{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true, capabilities: ["web_search"] },
|
|
54
|
+
]);
|
|
55
|
+
assert.deepEqual(Object.keys(out), ["gw/k1/pi-s2-9912"]);
|
|
56
|
+
const p = out["gw/k1/pi-s2-9912"]!;
|
|
57
|
+
assert.equal(p.url, "http://127.0.0.1:9920/peer/pi-s2-9912/");
|
|
58
|
+
assert.deepEqual(p.auth, { type: "bearer", token: TOKEN });
|
|
59
|
+
assert.deepEqual(p.capabilities, ["web_search"]);
|
|
60
|
+
assert.isTrue(p.viaGateway);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("defaults the key to 'default' when not provided", () => {
|
|
64
|
+
const out = mergeGatewayPeers({
|
|
65
|
+
gatewayUrl: GW,
|
|
66
|
+
token: TOKEN,
|
|
67
|
+
selfName: "s",
|
|
68
|
+
selfUrl: "http://127.0.0.1:9910",
|
|
69
|
+
entries: [{ name: "p", url: "/peer/p/", healthy: true }],
|
|
70
|
+
timeoutMs: 120_000,
|
|
71
|
+
});
|
|
72
|
+
assert.deepEqual(Object.keys(out), ["gw/default/p"]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it("skips self by registered name", () => {
|
|
76
|
+
const out = merge([
|
|
77
|
+
{ name: "pi-s2-9910", url: "/peer/pi-s2-9910/", healthy: true }, // self
|
|
78
|
+
{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true },
|
|
79
|
+
]);
|
|
80
|
+
assert.deepEqual(Object.keys(out), ["gw/k1/pi-s2-9912"]);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it("skips self by publicUrl port suffix (renamed session, stale auto-named entry)", () => {
|
|
84
|
+
const out = merge(
|
|
85
|
+
[
|
|
86
|
+
{ name: "pi-main", url: "/peer/pi-main/", healthy: true }, // self (pinned name)
|
|
87
|
+
{ name: "pi-s2-9910", url: "/peer/pi-s2-9910/", healthy: true }, // our stale auto-name
|
|
88
|
+
{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true },
|
|
89
|
+
],
|
|
90
|
+
{ name: "pi-main", url: "http://127.0.0.1:9910", autoName: "pi-s2-9910" },
|
|
91
|
+
);
|
|
92
|
+
assert.deepEqual(Object.keys(out), ["gw/k1/pi-s2-9912"]);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("isSelfEntry also matches an absolute publicUrl", () => {
|
|
96
|
+
assert.isTrue(
|
|
97
|
+
isSelfEntry(
|
|
98
|
+
{ name: "other", url: "http://10.1.2.3:9910/" },
|
|
99
|
+
{ name: "pi-main", url: "http://10.1.2.3:9910" },
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
assert.isFalse(
|
|
103
|
+
isSelfEntry(
|
|
104
|
+
{ name: "other", url: "http://10.1.2.3:9911/" },
|
|
105
|
+
{ name: "pi-main", url: "http://10.1.2.3:9910" },
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
it("skips unhealthy peers, keeps unknown (null) health", () => {
|
|
111
|
+
const out = merge([
|
|
112
|
+
{ name: "dead", url: "/peer/dead/", healthy: false },
|
|
113
|
+
{ name: "unknown", url: "/peer/unknown/", healthy: null },
|
|
114
|
+
{ name: "alive", url: "/peer/alive/" },
|
|
115
|
+
]);
|
|
116
|
+
assert.deepEqual(Object.keys(out).sort(), ["gw/k1/alive", "gw/k1/unknown"]);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
it("drops absolute/cross-origin urls (bearer token must only reach the gateway)", () => {
|
|
120
|
+
const out = merge([
|
|
121
|
+
{ name: "evil", url: "http://attacker.example/peer/evil/", healthy: true },
|
|
122
|
+
{ name: "ok", url: "/peer/ok/", healthy: true },
|
|
123
|
+
]);
|
|
124
|
+
assert.deepEqual(Object.keys(out), ["gw/k1/ok"]);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
it("cross-host same-port peer is NOT filtered (regression: bare -port suffix rule)", () => {
|
|
128
|
+
const out = merge(
|
|
129
|
+
[{ name: "other-host-9910", url: "/peer/other-host-9910/", healthy: true }],
|
|
130
|
+
{ name: "pi-main", url: "http://10.0.0.2:9910", autoName: "pi-main-9910" },
|
|
131
|
+
);
|
|
132
|
+
assert.deepEqual(Object.keys(out), ["gw/k1/other-host-9910"]);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("own auto-name entry IS filtered by exact match", () => {
|
|
136
|
+
const out = merge(
|
|
137
|
+
[{ name: "pi-main-9910", url: "/peer/pi-main-9910/", healthy: true }],
|
|
138
|
+
{ name: "pi-main", url: "http://10.0.0.2:9910", autoName: "pi-main-9910" },
|
|
139
|
+
);
|
|
140
|
+
assert.deepEqual(Object.keys(out), []);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("surfaces skill names when capabilities is absent or an object", () => {
|
|
144
|
+
const out = merge([
|
|
145
|
+
{ name: "a", url: "/peer/a/", healthy: true, capabilities: { streaming: true }, skills: [{ id: "coding", name: "coding" }] },
|
|
146
|
+
{ name: "b", url: "/peer/b/", healthy: true, skills: [{ id: "research" }] },
|
|
147
|
+
]);
|
|
148
|
+
assert.deepEqual(out["gw/k1/a"]!.capabilities, ["coding"]);
|
|
149
|
+
assert.deepEqual(out["gw/k1/b"]!.capabilities, ["research"]);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("gw-peer timeout comes from callTimeoutMs, not heartbeatSec (regression)", () => {
|
|
153
|
+
const out = mergeGatewayPeers({
|
|
154
|
+
gatewayUrl: GW,
|
|
155
|
+
token: TOKEN,
|
|
156
|
+
selfName: "s",
|
|
157
|
+
selfUrl: "http://127.0.0.1:9910",
|
|
158
|
+
entries: [{ name: "p", url: "/peer/p/", healthy: true }],
|
|
159
|
+
timeoutMs: 120_000,
|
|
160
|
+
key: "k1",
|
|
161
|
+
});
|
|
162
|
+
assert.equal(out["gw/k1/p"]!.timeout, 120_000);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it("drops malformed entries and tolerates a non-array peers field", () => {
|
|
166
|
+
assert.deepEqual(merge([{ url: "/peer/x/" }, { name: "a/b", url: "/x" }, { name: "no-url" }, null]), {});
|
|
167
|
+
assert.deepEqual(merge("not-an-array" as any), {});
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
describe("register backoff (429 / rate-limit)", () => {
|
|
172
|
+
const savedFetch = globalThis.fetch;
|
|
173
|
+
afterEach(() => {
|
|
174
|
+
globalThis.fetch = savedFetch as any;
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("backoffDelayMs: exponential growth, 5-min cap, jitter bounds, Retry-After wins when larger", () => {
|
|
178
|
+
for (let fails = 1; fails <= 4; fails++) {
|
|
179
|
+
const base = Math.min(300_000, 60_000 * 2 ** (fails - 1));
|
|
180
|
+
const d = backoffDelayMs(fails, 60_000, null);
|
|
181
|
+
assert.isAtLeast(d, Math.floor(base * 0.8));
|
|
182
|
+
assert.isAtMost(d, Math.ceil(base * 1.2));
|
|
183
|
+
}
|
|
184
|
+
// Deep failure chain clamps at the 5-min cap (±jitter).
|
|
185
|
+
assert.isAtMost(backoffDelayMs(50, 60_000, null), Math.ceil(300_000 * 1.2));
|
|
186
|
+
assert.isAtLeast(backoffDelayMs(50, 60_000, null), Math.floor(300_000 * 0.8));
|
|
187
|
+
// Retry-After only wins when larger than the jittered exponential (48–72s here).
|
|
188
|
+
assert.equal(backoffDelayMs(1, 60_000, 90), 90_000);
|
|
189
|
+
const ignored = backoffDelayMs(1, 60_000, -5); // non-positive Retry-After ignored
|
|
190
|
+
assert.isAtLeast(ignored, 48_000);
|
|
191
|
+
assert.isAtMost(ignored, 72_000);
|
|
192
|
+
// A buggy/hostile Retry-After (10 days) is capped — it must not suppress
|
|
193
|
+
// re-registration indefinitely.
|
|
194
|
+
assert.equal(backoffDelayMs(1, 60_000, 86_400), 300_000);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it("a failed register schedules a backoff; a later success resets it", async () => {
|
|
198
|
+
let status = 429;
|
|
199
|
+
globalThis.fetch = (async (url: any) => {
|
|
200
|
+
const u = String(url);
|
|
201
|
+
if (u.endsWith("/register")) return makeResp({}, status);
|
|
202
|
+
return makeResp({ peers: [] }, 200);
|
|
203
|
+
}) as any;
|
|
204
|
+
const gw = new GatewayUpstream(
|
|
205
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
206
|
+
() => ({}),
|
|
207
|
+
() => {},
|
|
208
|
+
() => {},
|
|
209
|
+
);
|
|
210
|
+
assert.isFalse(await gw.register("http://127.0.0.1:9911"));
|
|
211
|
+
assert.equal(gw["beatFails"], 1);
|
|
212
|
+
assert.isTrue(gw["backoffUntil"] > Date.now());
|
|
213
|
+
assert.isFalse(await gw.register("http://127.0.0.1:9911"));
|
|
214
|
+
assert.equal(gw["beatFails"], 2);
|
|
215
|
+
status = 200;
|
|
216
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911"));
|
|
217
|
+
assert.equal(gw["beatFails"], 0);
|
|
218
|
+
assert.equal(gw["backoffUntil"], 0);
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it("Retry-After header (seconds) extends the backoff", async () => {
|
|
222
|
+
globalThis.fetch = (async (url: any) => {
|
|
223
|
+
const u = String(url);
|
|
224
|
+
if (u.endsWith("/register")) return makeResp({}, 429, new Headers({ "retry-after": "90" }));
|
|
225
|
+
return makeResp({ peers: [] }, 200);
|
|
226
|
+
}) as any;
|
|
227
|
+
const gw = new GatewayUpstream(
|
|
228
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
229
|
+
() => ({}),
|
|
230
|
+
() => {},
|
|
231
|
+
() => {},
|
|
232
|
+
);
|
|
233
|
+
assert.isFalse(await gw.register("http://127.0.0.1:9911"));
|
|
234
|
+
// jittered exponential is 48–72s; the header must push it to ~90s
|
|
235
|
+
assert.isAtLeast(gw["backoffUntil"], Date.now() + 89_000);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
it("heartbeat (maybeBeat) skips while backed off, retries exactly once after it lapses", async () => {
|
|
239
|
+
const status = 429;
|
|
240
|
+
let registerCalls = 0;
|
|
241
|
+
globalThis.fetch = (async (url: any) => {
|
|
242
|
+
const u = String(url);
|
|
243
|
+
if (u.endsWith("/register")) {
|
|
244
|
+
registerCalls += 1;
|
|
245
|
+
return makeResp({}, status);
|
|
246
|
+
}
|
|
247
|
+
return makeResp({ peers: [] }, 200);
|
|
248
|
+
}) as any;
|
|
249
|
+
const gw = new GatewayUpstream(
|
|
250
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
251
|
+
() => ({}),
|
|
252
|
+
() => {},
|
|
253
|
+
() => {},
|
|
254
|
+
);
|
|
255
|
+
assert.isFalse(await gw.register("http://127.0.0.1:9911")); // registerCalls: 1, backoff armed
|
|
256
|
+
await gw["maybeBeat"]("http://127.0.0.1:9911"); // inside the backoff window → skipped
|
|
257
|
+
assert.equal(registerCalls, 1, "beat must not hit /register while backed off");
|
|
258
|
+
gw["backoffUntil"] = Date.now() - 1; // lapse
|
|
259
|
+
await gw["maybeBeat"]("http://127.0.0.1:9911");
|
|
260
|
+
assert.equal(registerCalls, 2, "exactly one retry after the backoff lapses");
|
|
261
|
+
});
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
describe("GatewayUpstream heartbeat → directory refresh", () => {
|
|
265
|
+
let originalFetch: typeof globalThis.fetch;
|
|
266
|
+
let calls: Array<{ method: string; url: string; auth?: string }>;
|
|
267
|
+
let overlay: Record<string, Peer>;
|
|
268
|
+
|
|
269
|
+
beforeEach(() => {
|
|
270
|
+
originalFetch = globalThis.fetch;
|
|
271
|
+
calls = [];
|
|
272
|
+
overlay = {};
|
|
273
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
274
|
+
calls.push({
|
|
275
|
+
method: init?.method || "GET",
|
|
276
|
+
url: String(url),
|
|
277
|
+
auth: init?.headers?.authorization,
|
|
278
|
+
});
|
|
279
|
+
const u = String(url);
|
|
280
|
+
if (u.endsWith("/register")) return makeResp({ status: "updated", caller_token: "agw_peer_ct_1" }, 200);
|
|
281
|
+
if (u.endsWith("/.well-known/agent.json")) {
|
|
282
|
+
return makeResp(
|
|
283
|
+
{
|
|
284
|
+
peers: [
|
|
285
|
+
{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true },
|
|
286
|
+
{ name: "self-1", url: "/peer/self-1/", healthy: true },
|
|
287
|
+
{ name: "dead", url: "/peer/dead/", healthy: false },
|
|
288
|
+
],
|
|
289
|
+
},
|
|
290
|
+
200,
|
|
291
|
+
);
|
|
292
|
+
}
|
|
293
|
+
return makeResp({}, 404);
|
|
294
|
+
}) as any;
|
|
295
|
+
});
|
|
296
|
+
afterEach(() => {
|
|
297
|
+
globalThis.fetch = originalFetch as any;
|
|
298
|
+
setGatewayPeers({});
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it("uses the per-peer caller token for gw/ overlay auth", async () => {
|
|
302
|
+
const gw = new GatewayUpstream(
|
|
303
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1" },
|
|
304
|
+
() => ({}),
|
|
305
|
+
() => {},
|
|
306
|
+
(peers) => (overlay = peers),
|
|
307
|
+
);
|
|
308
|
+
const ok = await gw.start("http://127.0.0.1:9911");
|
|
309
|
+
assert.isTrue(ok);
|
|
310
|
+
const snapshot = { ...overlay };
|
|
311
|
+
await gw.stop();
|
|
312
|
+
const dir = calls.find((c) => c.url.endsWith("/.well-known/agent.json"))!;
|
|
313
|
+
// Directory fetch still uses the SHARED token (read-only endpoint).
|
|
314
|
+
assert.equal(dir.auth, `Bearer ${TOKEN}`);
|
|
315
|
+
// But the overlay peer presents the per-peer CALLER token, so the
|
|
316
|
+
// gateway attributes calls to this peer's name.
|
|
317
|
+
assert.equal(snapshot["gw/k1/pi-s2-9912"]!.auth.token, "agw_peer_ct_1");
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
it("falls back to the shared token when /register omits caller_token", async () => {
|
|
321
|
+
// Older a2a-switchboard gateways don't issue a caller_token — the overlay must
|
|
322
|
+
// keep working with the shared token (a regression here would 401
|
|
323
|
+
// every gw/* outbound call).
|
|
324
|
+
const original = globalThis.fetch;
|
|
325
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
326
|
+
const u = String(url);
|
|
327
|
+
if (u.endsWith("/register")) return makeResp({ status: "updated" }, 200); // no caller_token
|
|
328
|
+
if (u.endsWith("/.well-known/agent.json")) {
|
|
329
|
+
return makeResp(
|
|
330
|
+
{ peers: [{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true }] },
|
|
331
|
+
200,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
return makeResp({}, 404);
|
|
335
|
+
}) as any;
|
|
336
|
+
try {
|
|
337
|
+
let fallbackOverlay: Record<string, import("../lib/config").Peer> = {};
|
|
338
|
+
const gw = new GatewayUpstream(
|
|
339
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1" },
|
|
340
|
+
() => ({}),
|
|
341
|
+
() => {},
|
|
342
|
+
(peers) => (fallbackOverlay = peers),
|
|
343
|
+
);
|
|
344
|
+
const ok = await gw.start("http://127.0.0.1:9911");
|
|
345
|
+
assert.isTrue(ok);
|
|
346
|
+
const snapshot = { ...fallbackOverlay };
|
|
347
|
+
await gw.stop();
|
|
348
|
+
assert.equal(snapshot["gw/k1/pi-s2-9912"]!.auth.token, TOKEN);
|
|
349
|
+
} finally {
|
|
350
|
+
globalThis.fetch = original as any;
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
|
|
354
|
+
it("heartbeats PATCH with the caller_token after the initial POST minted it", async () => {
|
|
355
|
+
const original = globalThis.fetch;
|
|
356
|
+
const seen: Array<{ method: string; auth?: string }> = [];
|
|
357
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
358
|
+
const u = String(url);
|
|
359
|
+
if (u.endsWith("/register")) {
|
|
360
|
+
const method = init?.method || "GET";
|
|
361
|
+
seen.push({ method, auth: init?.headers?.authorization });
|
|
362
|
+
// Method-aware: PATCH = heartbeat update (no mint), POST = mint.
|
|
363
|
+
if (method === "PATCH") return makeResp({ status: "updated", state: "accepted" }, 200);
|
|
364
|
+
return makeResp({ status: "updated", state: "accepted", caller_token: "agw_peer_ct_1" }, 200);
|
|
365
|
+
}
|
|
366
|
+
if (u.endsWith("/.well-known/agent.json"))
|
|
367
|
+
return makeResp({ peers: [] }, 200);
|
|
368
|
+
return makeResp({}, 404);
|
|
369
|
+
}) as any;
|
|
370
|
+
try {
|
|
371
|
+
const gw = new GatewayUpstream(
|
|
372
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
373
|
+
() => ({}),
|
|
374
|
+
() => {},
|
|
375
|
+
() => {},
|
|
376
|
+
);
|
|
377
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911")); // mint: POST, shared token
|
|
378
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // heartbeat: PATCH, caller_token
|
|
379
|
+
await gw.stop();
|
|
380
|
+
assert.equal(seen[0]!.method, "POST");
|
|
381
|
+
assert.equal(seen[0]!.auth, `Bearer ${TOKEN}`);
|
|
382
|
+
assert.equal(seen[1]!.method, "PATCH");
|
|
383
|
+
assert.equal(seen[1]!.auth, "Bearer agw_peer_ct_1");
|
|
384
|
+
assert.lengthOf(seen, 2); // no redundant POST after a successful PATCH
|
|
385
|
+
} finally {
|
|
386
|
+
globalThis.fetch = original as any;
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
it("PATCH 403 (revoked peer) does NOT fall back to POST", async () => {
|
|
391
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
392
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
393
|
+
fs.writeFileSync(path.join(dir, "a2a_gateways", "k1.json"), JSON.stringify({ name: "self-1", callerToken: "revoked-ct" }));
|
|
394
|
+
const original = globalThis.fetch;
|
|
395
|
+
const requests: Array<{ method: string; url: string }> = [];
|
|
396
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
397
|
+
requests.push({ method: init?.method || "GET", url: String(url).split("?")[0] });
|
|
398
|
+
if (String(url).endsWith("/register") && init?.method === "PATCH")
|
|
399
|
+
return makeResp({ error: "revoked" }, 403);
|
|
400
|
+
return makeResp({ status: "registered", caller_token: "minted-anyway" }, 200);
|
|
401
|
+
}) as any;
|
|
402
|
+
try {
|
|
403
|
+
const logs: string[] = [];
|
|
404
|
+
const gw = new GatewayUpstream(
|
|
405
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
406
|
+
() => ({}),
|
|
407
|
+
(m) => logs.push(String(m)),
|
|
408
|
+
() => {},
|
|
409
|
+
);
|
|
410
|
+
const ok = await gw.register("http://127.0.0.1:9911");
|
|
411
|
+
assert.isFalse(ok);
|
|
412
|
+
// Exactly one request (the PATCH) — no POST fallback for a 403.
|
|
413
|
+
assert.lengthOf(requests, 1);
|
|
414
|
+
assert.equal(requests[0]!.method, "PATCH");
|
|
415
|
+
assert.ok(logs.some((l) => l.includes("register failed: 403")), "failure logged");
|
|
416
|
+
await gw.stop();
|
|
417
|
+
} finally {
|
|
418
|
+
globalThis.fetch = original as any;
|
|
419
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
420
|
+
}
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
it("PATCH 409 (takeover mid-heartbeat) fails the beat — no rename, no POST", async () => {
|
|
424
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
425
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
426
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways", "k1"), { recursive: true });
|
|
427
|
+
fs.writeFileSync(path.join(dir, "a2a_gateways", "k1", "self-1.json"), JSON.stringify({ name: "self-1", callerToken: "live-ct" }));
|
|
428
|
+
const original = globalThis.fetch;
|
|
429
|
+
const requests: Array<{ method: string; body?: string }> = [];
|
|
430
|
+
const logs: string[] = [];
|
|
431
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
432
|
+
requests.push({ method: init?.method || "GET", body: init?.body });
|
|
433
|
+
if (String(url).endsWith("/register") && init?.method === "PATCH")
|
|
434
|
+
return makeResp({ error: "peer registered by another identity" }, 409);
|
|
435
|
+
return makeResp({ status: "registered" }, 200);
|
|
436
|
+
}) as any;
|
|
437
|
+
try {
|
|
438
|
+
const gw = new GatewayUpstream(
|
|
439
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
440
|
+
() => ({}),
|
|
441
|
+
(m) => logs.push(String(m)),
|
|
442
|
+
() => {},
|
|
443
|
+
);
|
|
444
|
+
const ok = await gw.register("http://127.0.0.1:9911");
|
|
445
|
+
assert.isFalse(ok);
|
|
446
|
+
// Exactly one request (the PATCH) with the ORIGINAL name — the unique-
|
|
447
|
+
// name self-heal must never trigger on a heartbeat 409 (it would split
|
|
448
|
+
// the gateway entry: old name holds it, new name re-registers).
|
|
449
|
+
assert.lengthOf(requests, 1);
|
|
450
|
+
assert.equal(requests[0]!.method, "PATCH");
|
|
451
|
+
assert.equal(JSON.parse(requests[0]!.body!).name, "self-1");
|
|
452
|
+
assert.equal(gw.registeredName, "self-1");
|
|
453
|
+
assert.ok(logs.some((l) => l.includes("register failed: 409")), "failure logged");
|
|
454
|
+
await gw.stop();
|
|
455
|
+
} finally {
|
|
456
|
+
globalThis.fetch = original as any;
|
|
457
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
458
|
+
}
|
|
459
|
+
});
|
|
460
|
+
|
|
461
|
+
it("register() bails without resurrecting state if stop() lands during body parse", async () => {
|
|
462
|
+
// Finding #8 (epoch-guard race): stop() during the awaited res.json()
|
|
463
|
+
// would slip past the post-send guard (epoch unchanged) and refreshPeers
|
|
464
|
+
// would re-capture the post-stop epoch and refill the overlay. The second
|
|
465
|
+
// guard must abort before mutating state.
|
|
466
|
+
let release!: () => void;
|
|
467
|
+
const deferred = new Promise<any>((res) => { release = () => res({ status: "registered", caller_token: "ct-minted" }); });
|
|
468
|
+
const original = globalThis.fetch;
|
|
469
|
+
const onPeersCalls: Array<Record<string, unknown>> = [];
|
|
470
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
471
|
+
const u = String(url);
|
|
472
|
+
if (u.endsWith("/register")) {
|
|
473
|
+
if (init?.method === "DELETE") return makeResp({ ok: true }, 200);
|
|
474
|
+
// 200 whose body only resolves AFTER stop() has run.
|
|
475
|
+
return { ok: true, status: 200, clone: undefined, json: () => deferred };
|
|
476
|
+
}
|
|
477
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
478
|
+
return makeResp({}, 404);
|
|
479
|
+
}) as any;
|
|
480
|
+
try {
|
|
481
|
+
const gw = new GatewayUpstream(
|
|
482
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
483
|
+
() => ({}),
|
|
484
|
+
() => {},
|
|
485
|
+
(peers) => onPeersCalls.push(peers),
|
|
486
|
+
);
|
|
487
|
+
const reg = gw.register("http://127.0.0.1:9911"); // in-flight
|
|
488
|
+
await gw.stop(); // lands while register awaits the deferred body
|
|
489
|
+
release();
|
|
490
|
+
const ok = await reg;
|
|
491
|
+
assert.isFalse(ok, "register must report failure after a mid-parse stop");
|
|
492
|
+
assert.isTrue(gw["stopped"], "stopped must stay true — no resurrection");
|
|
493
|
+
// stop() cleared the overlay via onPeers({}); register must NOT refill it.
|
|
494
|
+
assert.isAbove(onPeersCalls.length, 0, "stop() cleared the overlay");
|
|
495
|
+
assert.deepEqual(onPeersCalls[onPeersCalls.length - 1], {}, "last onPeers call is the empty overlay");
|
|
496
|
+
} finally {
|
|
497
|
+
globalThis.fetch = original as any;
|
|
498
|
+
}
|
|
499
|
+
});
|
|
500
|
+
|
|
501
|
+
it("409 self-heal renames → token persists under the RENAMED path, next session PATCHes with it", async () => {
|
|
502
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
503
|
+
const original = globalThis.fetch;
|
|
504
|
+
const seen: Array<{ method: string; auth?: string; name: string; cardName?: string }> = [];
|
|
505
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
506
|
+
const u = String(url);
|
|
507
|
+
if (u.endsWith("/register")) {
|
|
508
|
+
const body = JSON.parse(init?.body);
|
|
509
|
+
seen.push({ method: init?.method || "POST", auth: init?.headers?.authorization, name: body.name, cardName: body.card?.name });
|
|
510
|
+
if (body.name === "self-1" && (init?.method || "POST") === "POST" && !seen.some((s) => s.auth === "Bearer ct-new")) return makeResp({ error: "peer registered by another identity" }, 409);
|
|
511
|
+
if ((init?.method || "POST") === "POST") return makeResp({ status: "registered", caller_token: "ct-new" }, 200);
|
|
512
|
+
return makeResp({ status: "updated", state: "accepted" }, 200);
|
|
513
|
+
}
|
|
514
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
515
|
+
return makeResp({}, 404);
|
|
516
|
+
}) as any;
|
|
517
|
+
try {
|
|
518
|
+
const gw = new GatewayUpstream(
|
|
519
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
520
|
+
() => ({ name: "self-1" }), () => {}, () => {},
|
|
521
|
+
);
|
|
522
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // 409 → renamed POST mints
|
|
523
|
+
const renamed = gw.registeredName;
|
|
524
|
+
assert.notEqual(renamed, "self-1");
|
|
525
|
+
// State persisted under the RENAMED name; pre-rename file gone.
|
|
526
|
+
assert.isFalse(fs.existsSync(path.join(dir, "a2a_gateways", "k1", "self-1.json")));
|
|
527
|
+
const stateFile = path.join(dir, "a2a_gateways", "k1", `${renamed}.json`);
|
|
528
|
+
const j = JSON.parse(fs.readFileSync(stateFile, "utf8"));
|
|
529
|
+
assert.equal(j.name, renamed);
|
|
530
|
+
assert.equal(j.callerToken, "ct-new");
|
|
531
|
+
// Config name unchanged → no state under "self-1" → the next session
|
|
532
|
+
// re-runs the self-heal (deterministic: the stale entry persists). The
|
|
533
|
+
// important property — the RENAMED token persists and loads — is the
|
|
534
|
+
// stateFile assertion above, exercised by a same-named instance:
|
|
535
|
+
const gw3 = new GatewayUpstream(
|
|
536
|
+
{ url: GW, token: TOKEN, name: renamed, heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
537
|
+
() => ({}), () => {}, () => {},
|
|
538
|
+
);
|
|
539
|
+
assert.equal(gw3["callerToken"], "ct-new"); // loaded from the renamed file
|
|
540
|
+
assert.equal(seen[0]!.name, "self-1");
|
|
541
|
+
// Card name follows the RENAMED registration (409 rename consistency).
|
|
542
|
+
const renamedPost = seen.find((s) => s.method === "POST" && s.name === renamed)!;
|
|
543
|
+
assert.isOk(renamedPost, "renamed POST present");
|
|
544
|
+
assert.equal(renamedPost.cardName, renamed, "card.name must equal the registered name post-rename");
|
|
545
|
+
} finally {
|
|
546
|
+
globalThis.fetch = original as any;
|
|
547
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
548
|
+
}
|
|
549
|
+
});
|
|
550
|
+
|
|
551
|
+
it("logs directory failure only when the status changes (PATCH 200 + directory 401 × 2 cycles)", async () => {
|
|
552
|
+
const original = globalThis.fetch;
|
|
553
|
+
const logs: string[] = [];
|
|
554
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
555
|
+
const u = String(url);
|
|
556
|
+
if (u.endsWith("/register"))
|
|
557
|
+
return makeResp({ status: "updated", state: "accepted" }, 200);
|
|
558
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ error: "unauthorized" }, 401);
|
|
559
|
+
return makeResp({}, 404);
|
|
560
|
+
}) as any;
|
|
561
|
+
try {
|
|
562
|
+
const gw = new GatewayUpstream(
|
|
563
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
564
|
+
() => ({}),
|
|
565
|
+
(m) => logs.push(String(m)),
|
|
566
|
+
() => {},
|
|
567
|
+
);
|
|
568
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // cycle 1: dir 401 → log
|
|
569
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // cycle 2: dir 401 again → silent
|
|
570
|
+
const lines = logs.filter((l) => l.includes("peer directory refresh failed"));
|
|
571
|
+
assert.lengthOf(lines, 1); // exactly one line for a repeated identical failure
|
|
572
|
+
assert.match(lines[0]!, /peer directory refresh failed: 401/);
|
|
573
|
+
await gw.stop();
|
|
574
|
+
} finally {
|
|
575
|
+
globalThis.fetch = original as any;
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
it("PATCH 405 falls back to POST and sticks to POST afterwards (old switchboard)", async () => {
|
|
580
|
+
const original = globalThis.fetch;
|
|
581
|
+
const seen: Array<{ method: string }> = [];
|
|
582
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
583
|
+
const u = String(url);
|
|
584
|
+
if (u.endsWith("/register")) {
|
|
585
|
+
const method = init?.method || "GET";
|
|
586
|
+
seen.push({ method });
|
|
587
|
+
if (method === "PATCH") return makeResp({ error: "method not allowed" }, 405);
|
|
588
|
+
return makeResp({ status: "updated", caller_token: "agw_peer_ct_1" }, 200);
|
|
589
|
+
}
|
|
590
|
+
if (u.endsWith("/.well-known/agent.json"))
|
|
591
|
+
return makeResp({ peers: [] }, 200);
|
|
592
|
+
return makeResp({}, 404);
|
|
593
|
+
}) as any;
|
|
594
|
+
try {
|
|
595
|
+
const gw = new GatewayUpstream(
|
|
596
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false },
|
|
597
|
+
() => ({}),
|
|
598
|
+
() => {},
|
|
599
|
+
() => {},
|
|
600
|
+
);
|
|
601
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911")); // POST mints ct
|
|
602
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // PATCH 405 → POST fallback, succeeds
|
|
603
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // no flapping: straight POST
|
|
604
|
+
await gw.stop();
|
|
605
|
+
assert.deepEqual(seen.map((c) => c.method), ["POST", "PATCH", "POST", "POST"]);
|
|
606
|
+
} finally {
|
|
607
|
+
globalThis.fetch = original as any;
|
|
608
|
+
}
|
|
609
|
+
});
|
|
610
|
+
|
|
611
|
+
it("persisted caller_token → fresh GatewayUpstream heartbeats with PATCH immediately", async () => {
|
|
612
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
613
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
614
|
+
fs.writeFileSync(
|
|
615
|
+
path.join(dir, "a2a_gateways", "k1.json"),
|
|
616
|
+
JSON.stringify({ name: "self-1", callerToken: "persisted-ct" }),
|
|
617
|
+
);
|
|
618
|
+
const original = globalThis.fetch;
|
|
619
|
+
const seen: Array<{ method: string; auth?: string }> = [];
|
|
620
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
621
|
+
const u = String(url);
|
|
622
|
+
if (u.endsWith("/register")) {
|
|
623
|
+
seen.push({ method: init?.method || "GET", auth: init?.headers?.authorization });
|
|
624
|
+
return makeResp({ status: "updated" }, 200);
|
|
625
|
+
}
|
|
626
|
+
if (u.endsWith("/.well-known/agent.json"))
|
|
627
|
+
return makeResp({ peers: [] }, 200);
|
|
628
|
+
return makeResp({}, 404);
|
|
629
|
+
}) as any;
|
|
630
|
+
try {
|
|
631
|
+
const gw = new GatewayUpstream(
|
|
632
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
633
|
+
() => ({}),
|
|
634
|
+
() => {},
|
|
635
|
+
() => {},
|
|
636
|
+
);
|
|
637
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911"));
|
|
638
|
+
await gw.stop();
|
|
639
|
+
// Fresh instance loaded the persisted token → very first register is a
|
|
640
|
+
// PATCH (no mint POST), authed as the caller_token.
|
|
641
|
+
assert.lengthOf(seen, 1);
|
|
642
|
+
assert.equal(seen[0]!.method, "PATCH");
|
|
643
|
+
assert.equal(seen[0]!.auth, "Bearer persisted-ct");
|
|
644
|
+
} finally {
|
|
645
|
+
globalThis.fetch = original as any;
|
|
646
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
647
|
+
}
|
|
648
|
+
});
|
|
649
|
+
|
|
650
|
+
it("PATCH 401 (stale token) → fallback POST re-mints and re-persists", async () => {
|
|
651
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
652
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
653
|
+
const legacyStateFile = path.join(dir, "a2a_gateways", "k1.json");
|
|
654
|
+
const stateFile = path.join(dir, "a2a_gateways", "k1", "self-1.json");
|
|
655
|
+
fs.writeFileSync(legacyStateFile, JSON.stringify({ name: "self-1", callerToken: "stale-ct" }));
|
|
656
|
+
const original = globalThis.fetch;
|
|
657
|
+
const seen: Array<{ method: string; auth?: string }> = [];
|
|
658
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
659
|
+
const u = String(url);
|
|
660
|
+
if (u.endsWith("/register")) {
|
|
661
|
+
const method = init?.method || "GET";
|
|
662
|
+
seen.push({ method, auth: init?.headers?.authorization });
|
|
663
|
+
if (method === "PATCH" && init?.headers?.authorization === "Bearer stale-ct")
|
|
664
|
+
return makeResp({ error: "bad caller token" }, 401);
|
|
665
|
+
if (method === "PATCH") return makeResp({ status: "updated" }, 200); // re-minted token is valid
|
|
666
|
+
return makeResp({ status: "updated", caller_token: "re-minted-ct" }, 200);
|
|
667
|
+
}
|
|
668
|
+
if (u.endsWith("/.well-known/agent.json"))
|
|
669
|
+
return makeResp({ peers: [] }, 200);
|
|
670
|
+
return makeResp({}, 404);
|
|
671
|
+
}) as any;
|
|
672
|
+
try {
|
|
673
|
+
const gw = new GatewayUpstream(
|
|
674
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
675
|
+
() => ({}),
|
|
676
|
+
() => {},
|
|
677
|
+
() => {},
|
|
678
|
+
);
|
|
679
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911")); // PATCH 401 → POST re-mint
|
|
680
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // steady-state: PATCH with the re-minted token
|
|
681
|
+
await gw.stop();
|
|
682
|
+
assert.deepEqual(
|
|
683
|
+
seen.map((c) => `${c.method}:${c.auth === `Bearer ${TOKEN}` ? "shared" : c.auth}`),
|
|
684
|
+
["PATCH:Bearer stale-ct", "POST:shared", "PATCH:Bearer re-minted-ct"],
|
|
685
|
+
);
|
|
686
|
+
// Re-minted token hit the disk — the next restart skips POST.
|
|
687
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(stateFile, "utf8")), {
|
|
688
|
+
name: "self-1",
|
|
689
|
+
callerToken: "re-minted-ct",
|
|
690
|
+
});
|
|
691
|
+
} finally {
|
|
692
|
+
globalThis.fetch = original as any;
|
|
693
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
694
|
+
}
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
it("rejected caller_token (401, no re-mint) is cleared — overlay falls back to shared token", async () => {
|
|
698
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
699
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
700
|
+
fs.writeFileSync(
|
|
701
|
+
path.join(dir, "a2a_gateways", "k1.json"),
|
|
702
|
+
JSON.stringify({ name: "self-1", callerToken: "dead-ct" }),
|
|
703
|
+
);
|
|
704
|
+
const original = globalThis.fetch;
|
|
705
|
+
const seen: Array<{ method: string; auth?: string }> = [];
|
|
706
|
+
let overlay: Record<string, any> = {};
|
|
707
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
708
|
+
const u = String(url);
|
|
709
|
+
if (u.endsWith("/register")) {
|
|
710
|
+
seen.push({ method: init?.method || "GET", auth: init?.headers?.authorization });
|
|
711
|
+
if (init?.method === "PATCH") return makeResp({ error: "bad caller token" }, 401);
|
|
712
|
+
return makeResp({ status: "updated" }, 200); // old switchboard: no mint
|
|
713
|
+
}
|
|
714
|
+
if (u.endsWith("/.well-known/agent.json"))
|
|
715
|
+
return makeResp({ peers: [{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true }] }, 200);
|
|
716
|
+
return makeResp({}, 404);
|
|
717
|
+
}) as any;
|
|
718
|
+
try {
|
|
719
|
+
const gw = new GatewayUpstream(
|
|
720
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
721
|
+
() => ({}),
|
|
722
|
+
() => {},
|
|
723
|
+
(p) => (overlay = p),
|
|
724
|
+
);
|
|
725
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911")); // PATCH 401 → POST shared, no mint
|
|
726
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911")); // token still null → plain POST
|
|
727
|
+
// Dead token must not poison the overlay: gateway peers carry the shared token.
|
|
728
|
+
assert.equal(overlay["gw/k1/pi-s2-9912"]!.auth.token, TOKEN);
|
|
729
|
+
assert.deepEqual(
|
|
730
|
+
seen.map((c) => `${c.method}:${c.auth}`),
|
|
731
|
+
[
|
|
732
|
+
"PATCH:Bearer dead-ct",
|
|
733
|
+
"POST:Bearer " + TOKEN,
|
|
734
|
+
"POST:Bearer " + TOKEN, // no re-mint → stays POST
|
|
735
|
+
],
|
|
736
|
+
);
|
|
737
|
+
await gw.stop();
|
|
738
|
+
} finally {
|
|
739
|
+
globalThis.fetch = original as any;
|
|
740
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
it("PATCH 404 (entry deleted) → POST fallback re-registers in the same beat", async () => {
|
|
745
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
746
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
747
|
+
fs.writeFileSync(
|
|
748
|
+
path.join(dir, "a2a_gateways", "k1.json"),
|
|
749
|
+
JSON.stringify({ name: "self-1", callerToken: "old-ct" }),
|
|
750
|
+
);
|
|
751
|
+
const original = globalThis.fetch;
|
|
752
|
+
const seen: string[] = [];
|
|
753
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
754
|
+
const u = String(url);
|
|
755
|
+
if (u.endsWith("/register")) {
|
|
756
|
+
seen.push(init?.method || "GET");
|
|
757
|
+
if (init?.method === "PATCH") return makeResp({ error: "no such peer" }, 404);
|
|
758
|
+
return makeResp({ status: "registered", caller_token: "fresh-ct" }, 200);
|
|
759
|
+
}
|
|
760
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
761
|
+
return makeResp({}, 404);
|
|
762
|
+
}) as any;
|
|
763
|
+
try {
|
|
764
|
+
const gw = new GatewayUpstream(
|
|
765
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
766
|
+
() => ({}),
|
|
767
|
+
() => {},
|
|
768
|
+
() => {},
|
|
769
|
+
);
|
|
770
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911"));
|
|
771
|
+
assert.deepEqual(seen, ["PATCH", "POST"]); // 404 fell through, POST re-registered
|
|
772
|
+
// The a2a_gateways dir was auto-created and the re-minted token persisted.
|
|
773
|
+
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "a2a_gateways", "k1", "self-1.json"), "utf8")), {
|
|
774
|
+
name: "self-1",
|
|
775
|
+
callerToken: "fresh-ct",
|
|
776
|
+
});
|
|
777
|
+
await gw.stop();
|
|
778
|
+
} finally {
|
|
779
|
+
globalThis.fetch = original as any;
|
|
780
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
781
|
+
}
|
|
782
|
+
});
|
|
783
|
+
|
|
784
|
+
it("corrupt or foreign-name state file is ignored — POST mints from scratch", async () => {
|
|
785
|
+
for (const content of ["not-json{", JSON.stringify({ name: "other", callerToken: "x" })]) {
|
|
786
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
787
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
788
|
+
fs.writeFileSync(path.join(dir, "a2a_gateways", "k1.json"), content);
|
|
789
|
+
const original = globalThis.fetch;
|
|
790
|
+
const seen: string[] = [];
|
|
791
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
792
|
+
const u = String(url);
|
|
793
|
+
if (u.endsWith("/register")) {
|
|
794
|
+
seen.push(`${init?.method || "GET"}:${init?.headers?.authorization}`);
|
|
795
|
+
return makeResp({ status: "registered", caller_token: "minted-ct" }, 200);
|
|
796
|
+
}
|
|
797
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
798
|
+
return makeResp({}, 404);
|
|
799
|
+
}) as any;
|
|
800
|
+
try {
|
|
801
|
+
const gw = new GatewayUpstream(
|
|
802
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
803
|
+
() => ({}),
|
|
804
|
+
() => {},
|
|
805
|
+
() => {},
|
|
806
|
+
);
|
|
807
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911"));
|
|
808
|
+
// Ignored state → bootstrap POST with the shared token.
|
|
809
|
+
assert.deepEqual(seen, [`POST:Bearer ${TOKEN}`]);
|
|
810
|
+
await gw.stop();
|
|
811
|
+
} finally {
|
|
812
|
+
globalThis.fetch = original as any;
|
|
813
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
|
|
818
|
+
it("keeps caller tokens for concurrent peer names separate", async () => {
|
|
819
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
820
|
+
const original = globalThis.fetch;
|
|
821
|
+
const seen: string[] = [];
|
|
822
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
823
|
+
const u = String(url);
|
|
824
|
+
if (u.endsWith("/register")) {
|
|
825
|
+
seen.push(`${init?.method}:${init?.headers?.authorization}`);
|
|
826
|
+
const name = JSON.parse(init?.body).name;
|
|
827
|
+
return makeResp({ status: "registered", caller_token: `ct-${name}` }, 200);
|
|
828
|
+
}
|
|
829
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
830
|
+
return makeResp({}, 404);
|
|
831
|
+
}) as any;
|
|
832
|
+
try {
|
|
833
|
+
const cfg = (name: string) => ({ url: GW, token: TOKEN, name, key: "k1", channel: false, piDir: dir });
|
|
834
|
+
assert.isTrue(await new GatewayUpstream(cfg("self-1"), () => ({}), () => {}, () => {}).register("http://127.0.0.1:9911"));
|
|
835
|
+
assert.isTrue(await new GatewayUpstream(cfg("self-2"), () => ({}), () => {}, () => {}).register("http://127.0.0.1:9912"));
|
|
836
|
+
assert.isTrue(await new GatewayUpstream(cfg("self-1"), () => ({}), () => {}, () => {}).register("http://127.0.0.1:9911"));
|
|
837
|
+
assert.deepEqual(seen, [
|
|
838
|
+
`POST:Bearer ${TOKEN}`,
|
|
839
|
+
`POST:Bearer ${TOKEN}`,
|
|
840
|
+
"PATCH:Bearer ct-self-1",
|
|
841
|
+
]);
|
|
842
|
+
} finally {
|
|
843
|
+
globalThis.fetch = original as any;
|
|
844
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
845
|
+
}
|
|
846
|
+
});
|
|
847
|
+
|
|
848
|
+
it("deregisters with its caller token", async () => {
|
|
849
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
850
|
+
fs.mkdirSync(path.join(dir, "a2a_gateways"), { recursive: true });
|
|
851
|
+
fs.writeFileSync(path.join(dir, "a2a_gateways", "k1.json"), JSON.stringify({ name: "self-1", callerToken: "ct-self-1" }));
|
|
852
|
+
const original = globalThis.fetch;
|
|
853
|
+
let deleteAuth = "";
|
|
854
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
855
|
+
if (init?.method === "DELETE") deleteAuth = init.headers?.authorization;
|
|
856
|
+
if (String(url).endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
857
|
+
return makeResp({ status: "updated" }, 200);
|
|
858
|
+
}) as any;
|
|
859
|
+
try {
|
|
860
|
+
const gw = new GatewayUpstream(
|
|
861
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
862
|
+
() => ({}), () => {}, () => {},
|
|
863
|
+
);
|
|
864
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911"));
|
|
865
|
+
await gw.stop();
|
|
866
|
+
assert.equal(deleteAuth, "Bearer ct-self-1");
|
|
867
|
+
} finally {
|
|
868
|
+
globalThis.fetch = original as any;
|
|
869
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
870
|
+
}
|
|
871
|
+
});
|
|
872
|
+
|
|
873
|
+
it("initial POST 409 (stale name) self-heals with a unique name", async () => {
|
|
874
|
+
const dir = makeTempDir("pi-a2a-state-");
|
|
875
|
+
const original = globalThis.fetch;
|
|
876
|
+
const posts: string[] = [];
|
|
877
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
878
|
+
const u = String(url);
|
|
879
|
+
if (u.endsWith("/register") && (init?.method === "POST" || !init?.method)) {
|
|
880
|
+
posts.push(JSON.parse(init?.body).name);
|
|
881
|
+
if (posts.length === 1) return makeResp({ error: "peer registered by another identity" }, 409);
|
|
882
|
+
return makeResp({ status: "registered", caller_token: "ct-fresh" }, 200);
|
|
883
|
+
}
|
|
884
|
+
if (u.endsWith("/.well-known/agent.json")) return makeResp({ peers: [] }, 200);
|
|
885
|
+
return makeResp({}, 404);
|
|
886
|
+
}) as any;
|
|
887
|
+
try {
|
|
888
|
+
const gw = new GatewayUpstream(
|
|
889
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1", channel: false, piDir: dir },
|
|
890
|
+
() => ({}), () => {}, () => {},
|
|
891
|
+
);
|
|
892
|
+
assert.isTrue(await gw.register("http://127.0.0.1:9911"));
|
|
893
|
+
assert.lengthOf(posts, 2);
|
|
894
|
+
assert.notEqual(posts[1]!, posts[0]!);
|
|
895
|
+
await gw.stop();
|
|
896
|
+
} finally {
|
|
897
|
+
globalThis.fetch = original as any;
|
|
898
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
899
|
+
}
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
it("fetches the directory after registering and emits the merged overlay", async () => {
|
|
903
|
+
const gw = new GatewayUpstream(
|
|
904
|
+
{ url: GW, token: TOKEN, name: "self-1", heartbeatSec: 60, key: "k1" },
|
|
905
|
+
() => ({}),
|
|
906
|
+
() => {},
|
|
907
|
+
(peers) => (overlay = peers),
|
|
908
|
+
);
|
|
909
|
+
const ok = await gw.start("http://127.0.0.1:9911");
|
|
910
|
+
assert.isTrue(ok);
|
|
911
|
+
// Snapshot BEFORE stop — stop() clears the overlay by design.
|
|
912
|
+
const snapshot = { ...overlay };
|
|
913
|
+
await gw.stop();
|
|
914
|
+
const dir = calls.find((c) => c.url.endsWith("/.well-known/agent.json"))!;
|
|
915
|
+
assert.equal(dir.method, "GET");
|
|
916
|
+
assert.equal(dir.auth, `Bearer ${TOKEN}`);
|
|
917
|
+
assert.deepEqual(Object.keys(snapshot), ["gw/k1/pi-s2-9912"]); // self + dead filtered
|
|
918
|
+
assert.equal(snapshot["gw/k1/pi-s2-9912"]!.url, "http://127.0.0.1:9920/peer/pi-s2-9912/");
|
|
919
|
+
assert.deepEqual(overlay, {}); // cleared on stop
|
|
920
|
+
});
|
|
921
|
+
|
|
922
|
+
it("clears the overlay on stop and on a failed start", async () => {
|
|
923
|
+
const gw = new GatewayUpstream(
|
|
924
|
+
{ url: GW, token: TOKEN, name: "self-1" },
|
|
925
|
+
() => ({}),
|
|
926
|
+
() => {},
|
|
927
|
+
(peers) => (overlay = peers),
|
|
928
|
+
);
|
|
929
|
+
assert.isTrue(await gw.start("http://127.0.0.1:9911"));
|
|
930
|
+
assert.isNotEmpty(overlay);
|
|
931
|
+
await gw.stop();
|
|
932
|
+
assert.deepEqual(overlay, {});
|
|
933
|
+
|
|
934
|
+
// Failed start (gateway refusing registrations) must clear stale state.
|
|
935
|
+
globalThis.fetch = (async () => makeResp({ error: "unauthorized" }, 401)) as any;
|
|
936
|
+
assert.isFalse(await gw.start("http://127.0.0.1:9911"));
|
|
937
|
+
assert.deepEqual(overlay, {});
|
|
938
|
+
});
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
describe("outbound overlay routing", () => {
|
|
942
|
+
it("a2a_call('gw/…') works when the gateway is on a LAN/private IP (SSRF guard must not fire)", async () => {
|
|
943
|
+
const lanPeers = mergeGatewayPeers({
|
|
944
|
+
gatewayUrl: "http://192.168.1.50:9920",
|
|
945
|
+
token: TOKEN,
|
|
946
|
+
selfName: "s",
|
|
947
|
+
selfUrl: "http://127.0.0.1:9910",
|
|
948
|
+
entries: [{ name: "p", url: "/peer/p/", healthy: true }],
|
|
949
|
+
timeoutMs: 120_000,
|
|
950
|
+
key: "k1",
|
|
951
|
+
});
|
|
952
|
+
setGatewayPeers(lanPeers);
|
|
953
|
+
const of = globalThis.fetch;
|
|
954
|
+
const seen: string[] = [];
|
|
955
|
+
globalThis.fetch = (async (u: any) => {
|
|
956
|
+
seen.push(String(u));
|
|
957
|
+
return makeResp(
|
|
958
|
+
{ jsonrpc: "2.0", id: 1, result: { message: { role: "ROLE_AGENT", parts: [{ text: "lan ok" }] } } },
|
|
959
|
+
200,
|
|
960
|
+
);
|
|
961
|
+
}) as any;
|
|
962
|
+
const piDir2 = makeTempDir("pi-a2a-lan-");
|
|
963
|
+
const out = await a2aCall({ cfg: { ...DEFAULTS(), discovery: { ...(DEFAULTS() as any).discovery, gateway: { url: "http://192.168.1.50:9920", token: TOKEN } } } as any, piDir: piDir2, agent: "gw/k1/p", message: "hi" });
|
|
964
|
+
globalThis.fetch = of as any;
|
|
965
|
+
assert.include(out, "lan ok");
|
|
966
|
+
assert.equal(seen.filter((u) => u.startsWith("http://192.168.1.50:9920/peer/p")).length, 1);
|
|
967
|
+
});
|
|
968
|
+
|
|
969
|
+
let originalFetch: typeof globalThis.fetch;
|
|
970
|
+
let piDir: string;
|
|
971
|
+
|
|
972
|
+
beforeEach(() => {
|
|
973
|
+
originalFetch = globalThis.fetch;
|
|
974
|
+
piDir = makeTempDir("pi-a2a-gateway-");
|
|
975
|
+
metrics.reset();
|
|
976
|
+
});
|
|
977
|
+
afterEach(() => {
|
|
978
|
+
globalThis.fetch = originalFetch as any;
|
|
979
|
+
setGatewayPeers({});
|
|
980
|
+
});
|
|
981
|
+
|
|
982
|
+
it("overlay slices are independent per gateway key (stop one ≠ clear all)", () => {
|
|
983
|
+
updateGatewayPeers("work", { "gw/work/a": { url: "http://w/a", auth: { type: "none" }, timeout: 1000, capabilities: [] } });
|
|
984
|
+
updateGatewayPeers("lab", { "gw/lab/b": { url: "http://l/b", auth: { type: "none" }, timeout: 1000, capabilities: [] } });
|
|
985
|
+
assert.deepEqual(Object.keys(getGatewayPeers()).sort(), ["gw/lab/b", "gw/work/a"]);
|
|
986
|
+
// Clearing ONE gateway's slice must not touch the other's peers.
|
|
987
|
+
updateGatewayPeers("lab", {});
|
|
988
|
+
assert.deepEqual(Object.keys(getGatewayPeers()), ["gw/work/a"], "other gateway's overlay survives");
|
|
989
|
+
updateGatewayPeers("work", {});
|
|
990
|
+
assert.deepEqual(getGatewayPeers(), {}, "all cleared");
|
|
991
|
+
});
|
|
992
|
+
|
|
993
|
+
it("resolvePeer routes gw/<key>/<name> via the overlay; static peers win on collision", () => {
|
|
994
|
+
setGatewayPeers(
|
|
995
|
+
merge([{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true }]),
|
|
996
|
+
);
|
|
997
|
+
const cfg = DEFAULTS();
|
|
998
|
+
const p = resolvePeer(cfg, "gw/k1/pi-s2-9912");
|
|
999
|
+
assert.equal(p?.url, "http://127.0.0.1:9920/peer/pi-s2-9912/");
|
|
1000
|
+
assert.equal(p?.auth.type, "bearer");
|
|
1001
|
+
assert.equal(p?.auth.token, TOKEN);
|
|
1002
|
+
|
|
1003
|
+
cfg.peers["gw/static"] = {
|
|
1004
|
+
url: "http://static",
|
|
1005
|
+
auth: { type: "none" },
|
|
1006
|
+
timeout: 1000,
|
|
1007
|
+
capabilities: [],
|
|
1008
|
+
};
|
|
1009
|
+
setGatewayPeers({ "gw/static": { url: "http://overlay", auth: { type: "none" }, timeout: 1000, capabilities: [] } });
|
|
1010
|
+
assert.equal(resolvePeer(cfg, "gw/static")?.url, "http://static");
|
|
1011
|
+
assert.isNull(resolvePeer(cfg, "gw/unknown"));
|
|
1012
|
+
});
|
|
1013
|
+
|
|
1014
|
+
it("a2a_call('gw/…') posts JSON-RPC straight to the proxy URL with the gateway token", async () => {
|
|
1015
|
+
setGatewayPeers(
|
|
1016
|
+
merge([{ name: "pi-s2-9912", url: "/peer/pi-s2-9912/", healthy: true }]),
|
|
1017
|
+
);
|
|
1018
|
+
const requests: Array<{ method: string; url: string; auth?: string }> = [];
|
|
1019
|
+
globalThis.fetch = (async (url: any, init?: any) => {
|
|
1020
|
+
const h: Record<string, string> = Object.fromEntries(
|
|
1021
|
+
Object.entries(init?.headers ?? {}).map(([k, v]) => [k.toLowerCase(), String(v)]),
|
|
1022
|
+
);
|
|
1023
|
+
requests.push({
|
|
1024
|
+
method: init?.method || "GET",
|
|
1025
|
+
url: String(url),
|
|
1026
|
+
auth: h["authorization"],
|
|
1027
|
+
});
|
|
1028
|
+
return makeResp(
|
|
1029
|
+
{ jsonrpc: "2.0", id: 1, result: { message: { role: "ROLE_AGENT", parts: [{ text: "proxied reply" }] } } },
|
|
1030
|
+
200,
|
|
1031
|
+
);
|
|
1032
|
+
}) as any;
|
|
1033
|
+
|
|
1034
|
+
const out = await a2aCall({ cfg: DEFAULTS(), piDir, agent: "gw/k1/pi-s2-9912", message: "hi" });
|
|
1035
|
+
|
|
1036
|
+
// Exactly one request: the JSON-RPC POST pinned to the proxy URL — no
|
|
1037
|
+
// card GET (a proxied card would advertise the peer's direct URL and
|
|
1038
|
+
// bypass the gateway).
|
|
1039
|
+
assert.equal(requests.length, 1);
|
|
1040
|
+
assert.equal(requests[0]!.method, "POST");
|
|
1041
|
+
assert.equal(requests[0]!.url, "http://127.0.0.1:9920/peer/pi-s2-9912");
|
|
1042
|
+
assert.equal(requests[0]!.auth, `Bearer ${TOKEN}`);
|
|
1043
|
+
assert.include(out, "proxied reply");
|
|
1044
|
+
});
|
|
1045
|
+
});
|
|
1046
|
+
});
|
|
1047
|
+
|
|
1048
|
+
// ---------------------------------------------------------------------------
|
|
1049
|
+
// Reverse channel client
|
|
1050
|
+
// ---------------------------------------------------------------------------
|
|
1051
|
+
|
|
1052
|
+
import { ChannelClient } from "../lib/gateway";
|
|
1053
|
+
import * as http from "node:http";
|
|
1054
|
+
|
|
1055
|
+
describe("reverse channel client", () => {
|
|
1056
|
+
it("dispatches request envelopes to the local server and posts the response", async () => {
|
|
1057
|
+
// local A2A "server" (dispatch target)
|
|
1058
|
+
const localHits: Array<{ method: string; path: string; body?: string }> = [];
|
|
1059
|
+
const local = http.createServer((rq, rs) => {
|
|
1060
|
+
let body = "";
|
|
1061
|
+
rq.on("data", (c) => (body += c));
|
|
1062
|
+
rq.on("end", () => {
|
|
1063
|
+
localHits.push({ method: rq.method!, path: rq.url!, body });
|
|
1064
|
+
rs.writeHead(200, { "content-type": "application/json" });
|
|
1065
|
+
rs.end(JSON.stringify({ echoed: true }));
|
|
1066
|
+
});
|
|
1067
|
+
});
|
|
1068
|
+
await new Promise<void>((r) => local.listen(0, "127.0.0.1", r));
|
|
1069
|
+
const localPort = (local.address() as any).port;
|
|
1070
|
+
|
|
1071
|
+
// fake gateway: /channel SSE that pushes one request, /channel/response records
|
|
1072
|
+
const posted: any[] = [];
|
|
1073
|
+
const gw = http.createServer((rq, rs) => {
|
|
1074
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1075
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1076
|
+
const env = {
|
|
1077
|
+
id: 42,
|
|
1078
|
+
method: "POST",
|
|
1079
|
+
path: "/",
|
|
1080
|
+
headers: { "content-type": "application/json" },
|
|
1081
|
+
body_b64: Buffer.from('{"ping":1}').toString("base64"),
|
|
1082
|
+
};
|
|
1083
|
+
rs.write(`event: request\ndata: ${JSON.stringify(env)}\n\n`);
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
if (rq.url!.split("?")[0].startsWith("/channel/response/")) {
|
|
1087
|
+
let body = "";
|
|
1088
|
+
rq.on("data", (c) => (body += c));
|
|
1089
|
+
rq.on("end", () => {
|
|
1090
|
+
posted.push(JSON.parse(body));
|
|
1091
|
+
rs.writeHead(200); rs.end("ok");
|
|
1092
|
+
});
|
|
1093
|
+
return;
|
|
1094
|
+
}
|
|
1095
|
+
rs.writeHead(404); rs.end();
|
|
1096
|
+
});
|
|
1097
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1098
|
+
const gwPort = (gw.address() as any).port;
|
|
1099
|
+
|
|
1100
|
+
const epoch = { value: 0 };
|
|
1101
|
+
const cc = new ChannelClient(
|
|
1102
|
+
{ url: `http://127.0.0.1:${gwPort}`, token: TOKEN },
|
|
1103
|
+
`http://127.0.0.1:${localPort}`,
|
|
1104
|
+
() => {},
|
|
1105
|
+
epoch,
|
|
1106
|
+
);
|
|
1107
|
+
await cc.start();
|
|
1108
|
+
// give dispatch a beat
|
|
1109
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
1110
|
+
cc.stop();
|
|
1111
|
+
|
|
1112
|
+
assert.equal(localHits.length, 1);
|
|
1113
|
+
assert.equal(localHits[0]!.method, "POST");
|
|
1114
|
+
assert.equal(localHits[0]!.body, '{"ping":1}');
|
|
1115
|
+
assert.equal(posted.length, 1);
|
|
1116
|
+
assert.equal(posted[0]!.id, 42);
|
|
1117
|
+
assert.equal(posted[0]!.status, 200);
|
|
1118
|
+
assert.deepEqual(JSON.parse(Buffer.from(posted[0]!.body_b64, "base64").toString()), { echoed: true });
|
|
1119
|
+
|
|
1120
|
+
local.close(); gw.close();
|
|
1121
|
+
});
|
|
1122
|
+
|
|
1123
|
+
it("stop() prevents reconnect resurrection (epoch guard)", async () => {
|
|
1124
|
+
// gateway that accepts /channel then immediately closes the stream
|
|
1125
|
+
const gw = http.createServer((rq, rs) => {
|
|
1126
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1127
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1128
|
+
rs.end(); // immediate close → client would reconnect
|
|
1129
|
+
return;
|
|
1130
|
+
}
|
|
1131
|
+
rs.writeHead(404); rs.end();
|
|
1132
|
+
});
|
|
1133
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1134
|
+
const port = (gw.address() as any).port;
|
|
1135
|
+
let opens = 0;
|
|
1136
|
+
gw.on("request", () => { if (opens >= 0) opens += 1; });
|
|
1137
|
+
|
|
1138
|
+
const epoch = { value: 0 };
|
|
1139
|
+
const cc = new ChannelClient(
|
|
1140
|
+
{ url: `http://127.0.0.1:${port}`, token: TOKEN },
|
|
1141
|
+
"http://127.0.0.1:1",
|
|
1142
|
+
() => {},
|
|
1143
|
+
epoch,
|
|
1144
|
+
);
|
|
1145
|
+
const p = cc.start();
|
|
1146
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
1147
|
+
cc.stop();
|
|
1148
|
+
await p;
|
|
1149
|
+
const after = opens;
|
|
1150
|
+
await new Promise((r) => setTimeout(r, 1200));
|
|
1151
|
+
assert.equal(opens, after); // no reconnection attempts after stop
|
|
1152
|
+
gw.close();
|
|
1153
|
+
});
|
|
1154
|
+
|
|
1155
|
+
it("routes the channel-open lifecycle line to onStatus (not raw log)", async () => {
|
|
1156
|
+
const gw = http.createServer((rq, rs) => {
|
|
1157
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1158
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1159
|
+
rs.flushHeaders(); // send headers now; hold the stream open
|
|
1160
|
+
return; // hold the stream open
|
|
1161
|
+
}
|
|
1162
|
+
rs.writeHead(404); rs.end();
|
|
1163
|
+
});
|
|
1164
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1165
|
+
const gwPort = (gw.address() as any).port;
|
|
1166
|
+
const epoch = { value: 0 };
|
|
1167
|
+
const statuses: string[] = [];
|
|
1168
|
+
const logs: string[] = [];
|
|
1169
|
+
const cc = new ChannelClient(
|
|
1170
|
+
{ url: `http://127.0.0.1:${gwPort}`, token: TOKEN, name: "pi-s2-9915" },
|
|
1171
|
+
"http://127.0.0.1:1",
|
|
1172
|
+
(m) => logs.push(String(m)),
|
|
1173
|
+
epoch,
|
|
1174
|
+
(m) => statuses.push(String(m)),
|
|
1175
|
+
);
|
|
1176
|
+
await cc.start();
|
|
1177
|
+
await new Promise((r) => setTimeout(r, 150));
|
|
1178
|
+
cc.stop();
|
|
1179
|
+
assert.equal(statuses.length, 1, "channel open surfaced as status");
|
|
1180
|
+
assert.match(statuses[0]!, /channel open: \S+ as pi-s2-9915 \(firewall-safe receive\)/);
|
|
1181
|
+
assert.ok(!logs.some((l) => l.includes("channel open")), "not duplicated in raw log");
|
|
1182
|
+
gw.closeAllConnections?.();
|
|
1183
|
+
gw.close();
|
|
1184
|
+
});
|
|
1185
|
+
});
|
|
1186
|
+
|
|
1187
|
+
describe("reverse channel hardening", () => {
|
|
1188
|
+
it("drops envelopes with traversal paths", async () => {
|
|
1189
|
+
const hits: string[] = [];
|
|
1190
|
+
const local = http.createServer((rq, rs) => {
|
|
1191
|
+
hits.push(rq.url!);
|
|
1192
|
+
rs.writeHead(200); rs.end("ok");
|
|
1193
|
+
});
|
|
1194
|
+
await new Promise<void>((r) => local.listen(0, "127.0.0.1", r));
|
|
1195
|
+
const port = (local.address() as any).port;
|
|
1196
|
+
const gw = http.createServer((rq, rs) => {
|
|
1197
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1198
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1199
|
+
for (const path of ["../admin", "/../../etc/passwd", "/ok"]) {
|
|
1200
|
+
const env = { id: 7, method: "GET", path, headers: {}, body_b64: "" };
|
|
1201
|
+
rs.write(`event: request\ndata: ${JSON.stringify(env)}\n\n`);
|
|
1202
|
+
}
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
rs.writeHead(404); rs.end();
|
|
1206
|
+
});
|
|
1207
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1208
|
+
const gwPort = (gw.address() as any).port;
|
|
1209
|
+
const epoch = { value: 0 };
|
|
1210
|
+
const cc = new ChannelClient(
|
|
1211
|
+
{ url: `http://127.0.0.1:${gwPort}`, token: TOKEN },
|
|
1212
|
+
`http://127.0.0.1:${port}`,
|
|
1213
|
+
() => {},
|
|
1214
|
+
epoch,
|
|
1215
|
+
);
|
|
1216
|
+
await cc.start();
|
|
1217
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
1218
|
+
cc.stop();
|
|
1219
|
+
assert.deepEqual(hits, ["/ok"]); // traversal paths never reached local
|
|
1220
|
+
local.close(); gw.close();
|
|
1221
|
+
});
|
|
1222
|
+
|
|
1223
|
+
it("drops oversized envelopes without decoding", async () => {
|
|
1224
|
+
const hits: string[] = [];
|
|
1225
|
+
const local = http.createServer((rq, rs) => {
|
|
1226
|
+
hits.push(rq.url!);
|
|
1227
|
+
rs.writeHead(200); rs.end("ok");
|
|
1228
|
+
});
|
|
1229
|
+
await new Promise<void>((r) => local.listen(0, "127.0.0.1", r));
|
|
1230
|
+
const port = (local.address() as any).port;
|
|
1231
|
+
const gw = http.createServer((rq, rs) => {
|
|
1232
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1233
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1234
|
+
const env = { id: 8, method: "POST", path: "/", headers: {}, body_b64: "A".repeat(6_000_000) };
|
|
1235
|
+
rs.write(`event: request\ndata: ${JSON.stringify(env)}\n\n`);
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
rs.writeHead(404); rs.end();
|
|
1239
|
+
});
|
|
1240
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1241
|
+
const gwPort = (gw.address() as any).port;
|
|
1242
|
+
const epoch = { value: 0 };
|
|
1243
|
+
const cc = new ChannelClient(
|
|
1244
|
+
{ url: `http://127.0.0.1:${gwPort}`, token: TOKEN },
|
|
1245
|
+
`http://127.0.0.1:${port}`,
|
|
1246
|
+
() => {},
|
|
1247
|
+
epoch,
|
|
1248
|
+
);
|
|
1249
|
+
await cc.start();
|
|
1250
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
1251
|
+
cc.stop();
|
|
1252
|
+
assert.deepEqual(hits, []); // oversized never dispatched
|
|
1253
|
+
local.close(); gw.close();
|
|
1254
|
+
});
|
|
1255
|
+
|
|
1256
|
+
it("parses CRLF-delimited SSE frames with comments", async () => {
|
|
1257
|
+
const hits: string[] = [];
|
|
1258
|
+
const local = http.createServer((rq, rs) => {
|
|
1259
|
+
hits.push(rq.url!);
|
|
1260
|
+
rs.writeHead(200); rs.end("ok");
|
|
1261
|
+
});
|
|
1262
|
+
await new Promise<void>((r) => local.listen(0, "127.0.0.1", r));
|
|
1263
|
+
const port = (local.address() as any).port;
|
|
1264
|
+
const gw = http.createServer((rq, rs) => {
|
|
1265
|
+
if (rq.url!.split("?")[0] === "/channel") {
|
|
1266
|
+
rs.writeHead(200, { "content-type": "text/event-stream" });
|
|
1267
|
+
rs.write(": comment line\r\n");
|
|
1268
|
+
rs.write(`event: request\r\ndata: ${JSON.stringify({ id: 9, method: "GET", path: "/crlf", headers: {}, body_b64: "" })}\r\n\r\n`);
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
rs.writeHead(404); rs.end();
|
|
1272
|
+
});
|
|
1273
|
+
await new Promise<void>((r) => gw.listen(0, "127.0.0.1", r));
|
|
1274
|
+
const gwPort = (gw.address() as any).port;
|
|
1275
|
+
const epoch = { value: 0 };
|
|
1276
|
+
const cc = new ChannelClient(
|
|
1277
|
+
{ url: `http://127.0.0.1:${gwPort}`, token: TOKEN },
|
|
1278
|
+
`http://127.0.0.1:${port}`,
|
|
1279
|
+
() => {},
|
|
1280
|
+
epoch,
|
|
1281
|
+
);
|
|
1282
|
+
await cc.start();
|
|
1283
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
1284
|
+
cc.stop();
|
|
1285
|
+
assert.deepEqual(hits, ["/crlf"]);
|
|
1286
|
+
local.close(); gw.close();
|
|
1287
|
+
});
|
|
1288
|
+
});
|
|
1289
|
+
|
|
1290
|
+
describe("gateway diagnostics routing", () => {
|
|
1291
|
+
it("register failure goes to the error log, never the status surface", async () => {
|
|
1292
|
+
const statuses: string[] = [];
|
|
1293
|
+
const errors: string[] = [];
|
|
1294
|
+
const gw = new GatewayUpstream(
|
|
1295
|
+
{ url: "http://127.0.0.1:1", token: TOKEN, name: "self-1" }, // port 1: fetch rejects synchronously (bad-port blocklist)
|
|
1296
|
+
() => ({}),
|
|
1297
|
+
(m) => errors.push(String(m)),
|
|
1298
|
+
() => {},
|
|
1299
|
+
(m) => statuses.push(String(m)),
|
|
1300
|
+
);
|
|
1301
|
+
assert.isFalse(await gw.start("http://127.0.0.1:9911"));
|
|
1302
|
+
assert.ok(errors.some((e) => e.includes("register failed")), "failure surfaced as error");
|
|
1303
|
+
assert.equal(statuses.length, 0, "no status line for a failed registration");
|
|
1304
|
+
await gw.stop();
|
|
1305
|
+
});
|
|
1306
|
+
|
|
1307
|
+
it("failed start still arms the retry heartbeat (self-heal without restart)", async () => {
|
|
1308
|
+
const gw = new GatewayUpstream(
|
|
1309
|
+
{ url: "http://127.0.0.1:1", token: TOKEN, name: "self-1", channel: false }, // fetch rejects (bad-port blocklist — no connect attempted)
|
|
1310
|
+
() => ({}),
|
|
1311
|
+
() => {},
|
|
1312
|
+
() => {},
|
|
1313
|
+
);
|
|
1314
|
+
try {
|
|
1315
|
+
assert.isFalse(await gw.start("http://127.0.0.1:9911"));
|
|
1316
|
+
assert.ok((gw as unknown as { timer: unknown }).timer, "heartbeat armed despite failed start");
|
|
1317
|
+
} finally {
|
|
1318
|
+
await gw.stop();
|
|
1319
|
+
}
|
|
1320
|
+
assert.equal((gw as unknown as { timer: unknown }).timer, null, "stop() clears the retry heartbeat");
|
|
1321
|
+
});
|
|
1322
|
+
|
|
1323
|
+
it("network-error register logs carry the errno cause", async () => {
|
|
1324
|
+
const errors: string[] = [];
|
|
1325
|
+
const gw = new GatewayUpstream(
|
|
1326
|
+
{ url: "http://127.0.0.1:1", token: TOKEN, name: "self-1", channel: false },
|
|
1327
|
+
() => ({}),
|
|
1328
|
+
(m) => errors.push(String(m)),
|
|
1329
|
+
() => {},
|
|
1330
|
+
);
|
|
1331
|
+
assert.isFalse(await gw.start("http://127.0.0.1:9911"));
|
|
1332
|
+
assert.ok(
|
|
1333
|
+
errors.some((e) => /register failed: network error \((.+?)\)/.test(e)),
|
|
1334
|
+
`cause appended to network error: ${errors.join(" | ")}`,
|
|
1335
|
+
);
|
|
1336
|
+
await gw.stop();
|
|
1337
|
+
});
|
|
1338
|
+
|
|
1339
|
+
it("identical register failures log once (change-dedup), like directory refresh", async () => {
|
|
1340
|
+
const errors: string[] = [];
|
|
1341
|
+
const gw = new GatewayUpstream(
|
|
1342
|
+
{ url: "http://127.0.0.1:1", token: TOKEN, name: "self-1", channel: false },
|
|
1343
|
+
() => ({}),
|
|
1344
|
+
(m) => errors.push(String(m)),
|
|
1345
|
+
() => {},
|
|
1346
|
+
);
|
|
1347
|
+
await gw.register("http://127.0.0.1:9911");
|
|
1348
|
+
await gw.register("http://127.0.0.1:9911");
|
|
1349
|
+
assert.lengthOf(
|
|
1350
|
+
errors.filter((e) => e.includes("register failed")),
|
|
1351
|
+
1,
|
|
1352
|
+
"repeated identical failure must not repeat per beat",
|
|
1353
|
+
);
|
|
1354
|
+
await gw.stop();
|
|
1355
|
+
});
|
|
1356
|
+
|
|
1357
|
+
it("late self-heal beat registers, notifies onRegistered once, logs no failures", async () => {
|
|
1358
|
+
const errors: string[] = [];
|
|
1359
|
+
const registered: Array<{ name: string; state: string }> = [];
|
|
1360
|
+
const srv = http.createServer((req, res) => {
|
|
1361
|
+
let body = "";
|
|
1362
|
+
req.on("data", (c) => (body += c));
|
|
1363
|
+
req.on("end", () => {
|
|
1364
|
+
res.setHeader("content-type", "application/json");
|
|
1365
|
+
res.end(JSON.stringify({ state: "accepted" }));
|
|
1366
|
+
});
|
|
1367
|
+
});
|
|
1368
|
+
await new Promise<void>((r) => srv.listen(0, "127.0.0.1", r));
|
|
1369
|
+
const port = (srv.address() as { port: number }).port;
|
|
1370
|
+
await new Promise<void>((r) => srv.close(() => r())); // gateway down at session start
|
|
1371
|
+
const gw = new GatewayUpstream(
|
|
1372
|
+
{ url: `http://127.0.0.1:${port}`, token: TOKEN, name: "late-1", channel: false },
|
|
1373
|
+
() => ({ name: "late-1" }),
|
|
1374
|
+
(m) => errors.push(String(m)),
|
|
1375
|
+
() => {},
|
|
1376
|
+
undefined,
|
|
1377
|
+
(name, state) => registered.push({ name, state }),
|
|
1378
|
+
);
|
|
1379
|
+
const beat = (gw as unknown as { beat: (u: string) => Promise<void> }).beat;
|
|
1380
|
+
try {
|
|
1381
|
+
assert.isFalse(await gw.start(`http://127.0.0.1:${port}`));
|
|
1382
|
+
await new Promise<void>((r) => srv.listen(port, "127.0.0.1", r)); // gateway up BEFORE the beat (no connect/bind race)
|
|
1383
|
+
await beat.call(gw, `http://127.0.0.1:${port}`);
|
|
1384
|
+
assert.deepEqual(registered, [{ name: "late-1", state: "accepted" }],
|
|
1385
|
+
"first successful beat announces the registration");
|
|
1386
|
+
await beat.call(gw, `http://127.0.0.1:${port}`);
|
|
1387
|
+
assert.lengthOf(registered, 1, "onRegistered fires once (transition only)");
|
|
1388
|
+
assert.lengthOf(
|
|
1389
|
+
errors.filter((e) => e.includes("register failed")),
|
|
1390
|
+
1,
|
|
1391
|
+
"failed start logged once; recovered beats log nothing",
|
|
1392
|
+
);
|
|
1393
|
+
} finally {
|
|
1394
|
+
await gw.stop();
|
|
1395
|
+
await new Promise<void>((r) => srv.close(() => r()));
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1398
|
+
|
|
1399
|
+
it("EHOSTUNREACH on darwin hints Local Network privacy, once per cause", async () => {
|
|
1400
|
+
const realPlatform = process.platform;
|
|
1401
|
+
const originalFetch = globalThis.fetch;
|
|
1402
|
+
const errors: string[] = [];
|
|
1403
|
+
let gw1: GatewayUpstream | null = null;
|
|
1404
|
+
let gw2: GatewayUpstream | null = null;
|
|
1405
|
+
try {
|
|
1406
|
+
globalThis.fetch = (async () => {
|
|
1407
|
+
throw Object.assign(new TypeError("fetch failed"), { cause: { code: "EHOSTUNREACH" } });
|
|
1408
|
+
}) as any;
|
|
1409
|
+
Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
|
|
1410
|
+
|
|
1411
|
+
// Phase 1 — darwin: hint appended, dedup keeps it to one line.
|
|
1412
|
+
gw1 = new GatewayUpstream(
|
|
1413
|
+
{ url: "http://192.168.1.50:9920", token: TOKEN, name: "self-1", channel: false },
|
|
1414
|
+
() => ({}),
|
|
1415
|
+
(m) => errors.push(String(m)),
|
|
1416
|
+
() => {},
|
|
1417
|
+
);
|
|
1418
|
+
assert.isFalse(await gw1.register("http://127.0.0.1:9911"));
|
|
1419
|
+
assert.isFalse(await gw1.register("http://127.0.0.1:9911"));
|
|
1420
|
+
const failed = errors.filter((e) => e.includes("register failed"));
|
|
1421
|
+
assert.lengthOf(failed, 1, "repeated identical failure must not repeat per beat");
|
|
1422
|
+
assert.include(failed[0]!, "network error (EHOSTUNREACH)");
|
|
1423
|
+
assert.include(failed[0]!, "Local Network");
|
|
1424
|
+
assert.include(failed[0]!, "Privacy & Security");
|
|
1425
|
+
assert.notInclude(failed[0]!, "\n", "hint stays on a single line");
|
|
1426
|
+
assert.isBelow(failed[0]!.length, 320, "line stays length-capped");
|
|
1427
|
+
|
|
1428
|
+
// Phase 2 — non-darwin: EHOSTUNREACH is genuine routing, no hint.
|
|
1429
|
+
errors.length = 0;
|
|
1430
|
+
Object.defineProperty(process, "platform", { value: "linux", configurable: true });
|
|
1431
|
+
gw2 = new GatewayUpstream(
|
|
1432
|
+
{ url: "http://192.168.1.50:9920", token: TOKEN, name: "self-2", channel: false },
|
|
1433
|
+
() => ({}),
|
|
1434
|
+
(m) => errors.push(String(m)),
|
|
1435
|
+
() => {},
|
|
1436
|
+
);
|
|
1437
|
+
await gw2.register("http://127.0.0.1:9911");
|
|
1438
|
+
assert.ok(
|
|
1439
|
+
errors.some((e) => e.includes("EHOSTUNREACH") && !e.includes("Local Network")),
|
|
1440
|
+
`no darwin hint on linux: ${errors.join(" | ")}`,
|
|
1441
|
+
);
|
|
1442
|
+
} finally {
|
|
1443
|
+
if (gw1) await gw1.stop();
|
|
1444
|
+
if (gw2) await gw2.stop();
|
|
1445
|
+
Object.defineProperty(process, "platform", { value: realPlatform, configurable: true });
|
|
1446
|
+
globalThis.fetch = originalFetch as any;
|
|
1447
|
+
}
|
|
1448
|
+
});
|
|
1449
|
+
});
|